diff --git a/Chat.go b/Chat.go index a3a070e..775ee50 100644 --- a/Chat.go +++ b/Chat.go @@ -15,26 +15,21 @@ import ( ) func ChatPageHandler(c *fiber.Ctx) error { - authCookie := c.Cookies("jade-edgedb-auth-token", "") - - if authCookie != "" && !checkIfLogin() { - edgeClient = edgeClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": authCookie}) - } - var ( isSub bool limitReach bool ) - if !checkIfLogin() { + if c.Cookies("jade-edgedb-auth-token", "") == "" { + fmt.Println("Not logged in") isSub = false limitReach = false + return c.Render("chat", fiber.Map{"IsLogin": false, "HaveKey": false, "IsSubscribed": false, "IsLimiteReached": false}, "layouts/main") } else { - isSub = IsCurrentUserSubscribed() - limitReach = IsCurrentUserLimiteReached() + isSub = IsCurrentUserSubscribed(c) + limitReach = IsCurrentUserLimiteReached(c) + return c.Render("chat", fiber.Map{"IsLogin": checkIfLogin(c), "HaveKey": checkIfHaveKey(c), "IsSubscribed": isSub, "IsLimiteReached": limitReach}, "layouts/main") } - - return c.Render("chat", fiber.Map{"IsLogin": checkIfLogin(), "HaveKey": checkIfHaveKey(), "IsSubscribed": isSub, "IsLimiteReached": limitReach}, "layouts/main") } func DeleteMessageHandler(c *fiber.Ctx) error { @@ -47,7 +42,7 @@ func DeleteMessageHandler(c *fiber.Ctx) error { } // Delete all messages - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` WITH messageArea := (SELECT Message FILTER .id = $0).area DELETE Area @@ -58,19 +53,19 @@ func DeleteMessageHandler(c *fiber.Ctx) error { panic(err) } - return c.SendString(generateChatHTML()) + return c.SendString(generateChatHTML(c)) } func LoadChatHandler(c *fiber.Ctx) error { - deleteLLMtoDelete() + deleteLLMtoDelete(c) - if checkIfLogin() { - if IsCurrentUserLimiteReached() && !IsCurrentUserSubscribed() { - return c.SendString(generateLimitReachedChatHTML()) - } else if !checkIfHaveKey() { + if checkIfLogin(c) { + if IsCurrentUserLimiteReached(c) && !IsCurrentUserSubscribed(c) { + return c.SendString(generateLimitReachedChatHTML(c)) + } else if !checkIfHaveKey(c) { return c.SendString(generateEnterKeyChatHTML()) } - return c.SendString(generateChatHTML()) + return c.SendString(generateChatHTML(c)) } else { return c.SendString(generateWelcomeChatHTML()) } @@ -86,10 +81,10 @@ type TemplateMessage struct { ModelID string } -func generateChatHTML() string { +func generateChatHTML(c *fiber.Ctx) string { // Println the name of the current conversation var currentConv Conversation - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` SELECT global currentConversation { name }`, ¤tConv) if err != nil { fmt.Println("Error getting current conversation") @@ -100,7 +95,7 @@ func generateChatHTML() string { // Maybe redo that to be area by area because look like shit rn. It come from early stage of dev. It work tho soooo... var Messages []Message - err = edgeClient.Query(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Query(edgeCtx, ` SELECT Message { id, selected, @@ -189,7 +184,7 @@ func GetUserMessageHandler(c *fiber.Ctx) error { messageUUID, _ := edgedb.ParseUUID(id) var selectedMessage Message - err := edgeClient.QuerySingle(context.Background(), ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(context.Background(), ` SELECT Message { content } @@ -217,7 +212,7 @@ func GetMessageContentHandler(c *fiber.Ctx) error { messageUUID, _ := edgedb.ParseUUID(messageId) var selectedMessage Message - err := edgeClient.QuerySingle(context.Background(), ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(context.Background(), ` SELECT Message { content, llm : { @@ -251,7 +246,7 @@ func GetMessageContentHandler(c *fiber.Ctx) error { out += "" // Update the selected value of messages in the database - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` WITH m := (SELECT Message FILTER .id = $0) UPDATE Message FILTER .area = m.area @@ -261,7 +256,7 @@ func GetMessageContentHandler(c *fiber.Ctx) error { panic(err) } - _ = edgeClient.Execute(edgeCtx, ` + _ = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` UPDATE Message FILTER .id = $0 SET {selected := true}; @@ -435,17 +430,17 @@ func generateTermAndServiceChatHTML() string { return htmlString } -func generateLimitReachedChatHTML() string { +func generateLimitReachedChatHTML(c *fiber.Ctx) string { welcomeMessage := `You have reached the maximum number of messages for a free account. Please upgrade your account to continue using JADE.` var result User - err := edgeClient.QuerySingle(edgeCtx, "SELECT global currentUser { stripe_id, email } LIMIT 1;", &result) + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, "SELECT global currentUser { stripe_id, email } LIMIT 1;", &result) if err != nil { fmt.Println("Error getting current user") panic(err) } - clientSecretSession := CreateClientSecretSession() + clientSecretSession := CreateClientSecretSession(c) // TODO Replace by live API call stripeTable := ` @@ -486,7 +481,7 @@ func GetEditMessageFormHandler(c *fiber.Ctx) error { idUUID, _ := edgedb.ParseUUID(id) var message Message - err := edgeClient.QuerySingle(context.Background(), ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(context.Background(), ` SELECT Message { content } FILTER .id = $0; `, &message, idUUID) @@ -521,7 +516,7 @@ func RedoMessageHandler(c *fiber.Ctx) error { } var message Message - err = edgeClient.QuerySingle(context.Background(), ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(context.Background(), ` SELECT Message { content } FILTER .id = $0; `, &message, messageUUID) @@ -531,7 +526,7 @@ func RedoMessageHandler(c *fiber.Ctx) error { } // Delete messages - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` WITH messageArea := (SELECT Message FILTER .id = $0).area DELETE Area @@ -542,7 +537,7 @@ func RedoMessageHandler(c *fiber.Ctx) error { panic(err) } - return c.SendString(GeneratePlaceholderHTML(message.Content, selectedLLMIds, false)) + return c.SendString(GeneratePlaceholderHTML(c, message.Content, selectedLLMIds, false)) } func EditMessageHandler(c *fiber.Ctx) error { @@ -562,7 +557,7 @@ func EditMessageHandler(c *fiber.Ctx) error { } // Delete messages - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` WITH messageArea := (SELECT Message FILTER .id = $0).area DELETE Area @@ -573,12 +568,12 @@ func EditMessageHandler(c *fiber.Ctx) error { panic(err) } - return c.SendString(GeneratePlaceholderHTML(message, selectedLLMIds, true)) + return c.SendString(GeneratePlaceholderHTML(c, message, selectedLLMIds, true)) } func ClearChatHandler(c *fiber.Ctx) error { // Delete the default conversation - err := edgeClient.Execute(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` DELETE Area FILTER .conversation = global currentConversation; `) @@ -587,12 +582,12 @@ func ClearChatHandler(c *fiber.Ctx) error { panic(err) } - return c.SendString(generateChatHTML()) + return c.SendString(generateChatHTML(c)) } // Popover stuff func LoadUsageKPIHandler(c *fiber.Ctx) error { - if !checkIfLogin() || !checkIfHaveKey() { + if !checkIfLogin(c) || !checkIfHaveKey(c) { return c.SendString("") } @@ -624,7 +619,7 @@ func LoadUsageKPIHandler(c *fiber.Ctx) error { } var usages []UsageKPI - err = edgeClient.Query(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Query(edgeCtx, ` WITH U := ( SELECT Usage @@ -675,11 +670,11 @@ func LoadUsageKPIHandler(c *fiber.Ctx) error { return c.SendString(out) } -func GenerateModelPopoverHTML(refresh bool) string { - openaiExists, anthropicExists, mistralExists, groqExists, gooseaiExists, googleExists := getExistingKeys() +func GenerateModelPopoverHTML(refresh bool, c *fiber.Ctx) string { + openaiExists, anthropicExists, mistralExists, groqExists, gooseaiExists, googleExists := getExistingKeys(c) var llms []LLM - err := edgeClient.Query(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Query(edgeCtx, ` SELECT LLM { id, name, @@ -702,10 +697,10 @@ func GenerateModelPopoverHTML(refresh bool) string { panic(err) } - modelInfos := GetAvailableModels() + modelInfos := GetAvailableModels(c) out, err := modelPopoverTmpl.Execute(pongo2.Context{ - "IsLogin": checkIfLogin(), + "IsLogin": checkIfLogin(c), "OpenaiExists": openaiExists, "AnthropicExists": anthropicExists, "MistralExists": mistralExists, @@ -716,7 +711,7 @@ func GenerateModelPopoverHTML(refresh bool) string { "LLMs": llms, "ModelInfos": modelInfos, "DeleteUpdate": refresh, - "IsSub": IsCurrentUserSubscribed(), + "IsSub": IsCurrentUserSubscribed(c), }) if err != nil { fmt.Println("Error generating model popover") @@ -726,15 +721,15 @@ func GenerateModelPopoverHTML(refresh bool) string { } func LoadModelSelectionHandler(c *fiber.Ctx) error { - if !checkIfLogin() || !checkIfHaveKey() { + if !checkIfLogin(c) || !checkIfHaveKey(c) { return c.SendString("") } - return c.SendString(GenerateModelPopoverHTML(false)) + return c.SendString(GenerateModelPopoverHTML(false, c)) } -func GenerateConversationPopoverHTML(isActive bool) string { +func GenerateConversationPopoverHTML(isActive bool, c *fiber.Ctx) string { var conversations []Conversation - err := edgeClient.Query(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Query(edgeCtx, ` SELECT Conversation { name, position, @@ -769,25 +764,25 @@ func GenerateConversationPopoverHTML(isActive bool) string { } func LoadConversationSelectionHandler(c *fiber.Ctx) error { - if !checkIfLogin() || !checkIfHaveKey() { + if !checkIfLogin(c) || !checkIfHaveKey(c) { return c.SendString("") } - return c.SendString(GenerateConversationPopoverHTML(false)) + return c.SendString(GenerateConversationPopoverHTML(false, c)) } func RefreshConversationSelectionHandler(c *fiber.Ctx) error { IsActive := c.FormValue("IsActive") == "true" - return c.SendString(GenerateConversationPopoverHTML(!IsActive)) + return c.SendString(GenerateConversationPopoverHTML(!IsActive, c)) } func LoadSettingsHandler(c *fiber.Ctx) error { - if !checkIfLogin() { + if !checkIfLogin(c) { return c.SendString("") } var user User - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` SELECT User { email } @@ -803,10 +798,10 @@ func LoadSettingsHandler(c *fiber.Ctx) error { stripeSubLink := "https://billing.stripe.com/p/login/test_eVa5kC1q7dogaaIcMM?prefilled_email=" + user.Email - openaiExists, anthropicExists, mistralExists, groqExists, gooseaiExists, googleExists := getExistingKeys() + openaiExists, anthropicExists, mistralExists, groqExists, gooseaiExists, googleExists := getExistingKeys(c) out, err := settingPopoverTmpl.Execute(pongo2.Context{ - "IsLogin": checkIfLogin(), + "IsLogin": checkIfLogin(c), "OpenaiExists": openaiExists, "AnthropicExists": anthropicExists, "MistralExists": mistralExists, @@ -814,7 +809,7 @@ func LoadSettingsHandler(c *fiber.Ctx) error { "GooseaiExists": gooseaiExists, "GoogleExists": googleExists, "AnyExists": openaiExists || anthropicExists || mistralExists || groqExists || gooseaiExists || googleExists, - "IsSub": IsCurrentUserSubscribed(), + "IsSub": IsCurrentUserSubscribed(c), "StripeSubLink": stripeSubLink, }) if err != nil { @@ -830,7 +825,7 @@ func CreateConversationHandler(c *fiber.Ctx) error { name = "New Conversation" } - err := edgeClient.Execute(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` WITH C := ( SELECT Conversation @@ -847,7 +842,7 @@ func CreateConversationHandler(c *fiber.Ctx) error { panic(err) } - return c.SendString(GenerateConversationPopoverHTML(true)) + return c.SendString(GenerateConversationPopoverHTML(true, c)) } func DeleteConversationHandler(c *fiber.Ctx) error { @@ -859,7 +854,7 @@ func DeleteConversationHandler(c *fiber.Ctx) error { panic(err) } - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` DELETE Conversation FILTER .user = global currentUser AND .id = $0; `, conversationUUID) @@ -869,7 +864,7 @@ func DeleteConversationHandler(c *fiber.Ctx) error { } // Select the default conversation - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` UPDATE Conversation FILTER .user = global currentUser AND .name = 'Default' SET { @@ -885,7 +880,7 @@ func DeleteConversationHandler(c *fiber.Ctx) error { ` - return c.SendString(GenerateConversationPopoverHTML(true) + reloadChatTriggerHTML) + return c.SendString(GenerateConversationPopoverHTML(true, c) + reloadChatTriggerHTML) } func SelectConversationHandler(c *fiber.Ctx) error { @@ -896,7 +891,7 @@ func SelectConversationHandler(c *fiber.Ctx) error { panic(err) } - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` UPDATE Conversation FILTER .user = global currentUser SET { @@ -908,7 +903,7 @@ func SelectConversationHandler(c *fiber.Ctx) error { panic(err) } - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` UPDATE Conversation FILTER .user = global currentUser AND .id = $0 SET { @@ -920,16 +915,13 @@ func SelectConversationHandler(c *fiber.Ctx) error { panic(err) } - edgeClient = edgeClient.WithoutGlobals().WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token")}) - - return c.SendString(generateChatHTML()) + return c.SendString(generateChatHTML(c)) } func ArchiveDefaultConversationHandler(c *fiber.Ctx) error { - edgeClient = edgeClient.WithoutGlobals().WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token")}) name := c.FormValue("conversation-name-input") - err := edgeClient.Execute(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` UPDATE Conversation FILTER .user = global currentUser AND .name = 'Default' SET { @@ -941,7 +933,7 @@ func ArchiveDefaultConversationHandler(c *fiber.Ctx) error { panic(err) } - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` WITH C := ( SELECT Conversation @@ -958,5 +950,5 @@ func ArchiveDefaultConversationHandler(c *fiber.Ctx) error { panic(err) } - return c.SendString(GenerateConversationPopoverHTML(true)) + return c.SendString(GenerateConversationPopoverHTML(true, c)) } diff --git a/LLM.go b/LLM.go index 2519375..664236b 100644 --- a/LLM.go +++ b/LLM.go @@ -20,7 +20,7 @@ func deleteLLM(c *fiber.Ctx) error { for _, id := range selectedLLMIds { idUUID, _ := edgedb.ParseUUID(id) - err := edgeClient.Execute(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` UPDATE LLM FILTER .id = $0 AND .user = global currentUser SET { @@ -33,13 +33,13 @@ func deleteLLM(c *fiber.Ctx) error { } } - deleteLLMtoDelete() + deleteLLMtoDelete(c) - return c.SendString(GenerateModelPopoverHTML(true)) + return c.SendString(GenerateModelPopoverHTML(true, c)) } -func deleteLLMtoDelete() { - err := edgeClient.Execute(edgeCtx, ` +func deleteLLMtoDelete(c *fiber.Ctx) { + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` delete LLM filter .to_delete = true and not exists( select Message filter .llm = LLM @@ -63,7 +63,7 @@ func createLLM(c *fiber.Ctx) error { customID := c.FormValue("model-cid-input") if modelID == "custom" { - err := edgeClient.Execute(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` WITH countLLM := count((SELECT LLM FILTER .user = global currentUser)) INSERT LLM { @@ -91,7 +91,7 @@ func createLLM(c *fiber.Ctx) error { panic(err) } } else { - err := edgeClient.Execute(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` WITH countLLM := count((SELECT LLM FILTER .user = global currentUser)) INSERT LLM { @@ -109,7 +109,7 @@ func createLLM(c *fiber.Ctx) error { } } - return c.SendString(GenerateModelPopoverHTML(true)) + return c.SendString(GenerateModelPopoverHTML(true, c)) } type PositionUpdate struct { @@ -130,7 +130,7 @@ func updateLLMPositionBatch(c *fiber.Ctx) error { panic(err) } - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` UPDATE LLM FILTER .id = $0 AND .user = global currentUser SET { @@ -161,7 +161,7 @@ func updateConversationPositionBatch(c *fiber.Ctx) error { panic(err) } - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` UPDATE Conversation FILTER .id = $0 AND .user = global currentUser SET { diff --git a/Request.go b/Request.go index 02f6855..94da52d 100644 --- a/Request.go +++ b/Request.go @@ -41,16 +41,16 @@ func GeneratePlaceholderHandler(c *fiber.Ctx) error { panic(err) } - return c.SendString(GeneratePlaceholderHTML(message, selectedLLMIds, true)) + return c.SendString(GeneratePlaceholderHTML(c, message, selectedLLMIds, true)) } -func GeneratePlaceholderHTML(message string, selectedLLMIds []string, with_user_message bool) string { +func GeneratePlaceholderHTML(c *fiber.Ctx, message string, selectedLLMIds []string, with_user_message bool) string { var selectedLLMs []LLM var selectedLLM LLM for _, id := range selectedLLMIds { idUUID, _ := edgedb.ParseUUID(id) - err := edgeClient.QuerySingle(context.Background(), ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(context.Background(), ` SELECT LLM { id, name, @@ -81,11 +81,11 @@ func GeneratePlaceholderHTML(message string, selectedLLMIds []string, with_user_ } lastSelectedLLMs = selectedLLMs - _, position := insertArea() + _, position := insertArea(c) out := "" if with_user_message { - messageID := insertUserMessage(message) + messageID := insertUserMessage(c, message) messageOut, _ := userTmpl.Execute(pongo2.Context{"Content": markdownToHTML(message), "ID": messageID.String()}) out += messageOut } @@ -99,7 +99,7 @@ func GeneratePlaceholderHTML(message string, selectedLLMIds []string, with_user_ func GenerateMultipleMessagesHandler(c *fiber.Ctx) error { // Step 2 generate multiple messages // And send them one by one using events - insertArea() + insertArea(c) selectedLLMs := lastSelectedLLMs // Create a wait group to synchronize the goroutines @@ -121,7 +121,7 @@ func GenerateMultipleMessagesHandler(c *fiber.Ctx) error { defer cancel() // Ensure the context is cancelled to free resources // Determine which message function to call based on the model - var addMessageFunc func(selectedLLM LLM, selected bool) edgedb.UUID + var addMessageFunc func(c *fiber.Ctx, selectedLLM LLM, selected bool) edgedb.UUID switch selectedLLMs[idx].Model.Company.Name { case "openai": addMessageFunc = addOpenaiMessage @@ -141,11 +141,11 @@ func GenerateMultipleMessagesHandler(c *fiber.Ctx) error { var messageID edgedb.UUID if addMessageFunc != nil { - messageID = addMessageFunc(selectedLLMs[idx], idx == 0) + messageID = addMessageFunc(c, selectedLLMs[idx], idx == 0) } var message Message - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` SELECT Message { id, content, @@ -247,9 +247,9 @@ func GenerateMultipleMessagesHandler(c *fiber.Ctx) error { return c.SendString("") } -func addUsage(inputCost float32, outputCost float32, inputToken int32, outputToken int32, modelID string) { +func addUsage(c *fiber.Ctx, inputCost float32, outputCost float32, inputToken int32, outputToken int32, modelID string) { // Create a new usage - err := edgeClient.Execute(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` INSERT Usage { input_cost := $0, output_cost := $1, diff --git a/RequestAnthropic.go b/RequestAnthropic.go index f7385a9..dce82ec 100644 --- a/RequestAnthropic.go +++ b/RequestAnthropic.go @@ -8,6 +8,7 @@ import ( "net/http" "github.com/edgedb/edgedb-go" + "github.com/gofiber/fiber/v2" ) type AnthropicChatCompletionRequest struct { @@ -36,19 +37,19 @@ type AnthropicUsage struct { OutputTokens int32 `json:"output_tokens"` } -func addAnthropicMessage(llm LLM, selected bool) edgedb.UUID { - Messages := getAllSelectedMessages() +func addAnthropicMessage(c *fiber.Ctx, llm LLM, selected bool) edgedb.UUID { + Messages := getAllSelectedMessages(c) - chatCompletion, err := RequestAnthropic(llm.Model.ModelID, Messages, int(llm.Model.MaxToken), float64(llm.Temperature), llm.Context) + chatCompletion, err := RequestAnthropic(c, llm.Model.ModelID, Messages, int(llm.Model.MaxToken), float64(llm.Temperature), llm.Context) if err != nil { fmt.Println("Error fetching user profile") panic(err) } else if len(chatCompletion.Content) == 0 { fmt.Println("No response from Anthropic") - id := insertBotMessage("No response from Anthropic", selected, llm.ID) + id := insertBotMessage(c, "No response from Anthropic", selected, llm.ID) return id } else { - id := insertBotMessage(chatCompletion.Content[0].Text, selected, llm.ID) + id := insertBotMessage(c, chatCompletion.Content[0].Text, selected, llm.ID) return id } } @@ -108,11 +109,11 @@ func TestAnthropicKey(apiKey string) bool { return true } -func RequestAnthropic(model string, messages []Message, maxTokens int, temperature float64, context string) (AnthropicChatCompletionResponse, error) { +func RequestAnthropic(c *fiber.Ctx, model string, messages []Message, maxTokens int, temperature float64, context string) (AnthropicChatCompletionResponse, error) { var apiKey struct { Key string `edgedb:"key"` } - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` SELECT Key { key } @@ -166,7 +167,7 @@ func RequestAnthropic(model string, messages []Message, maxTokens int, temperatu } var usedModelInfo ModelInfo - err = edgeClient.QuerySingle(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` SELECT ModelInfo { inputPrice, outputPrice @@ -180,7 +181,7 @@ func RequestAnthropic(model string, messages []Message, maxTokens int, temperatu var inputCost float32 = float32(chatCompletionResponse.Usage.InputTokens) * usedModelInfo.InputPrice var outputCost float32 = float32(chatCompletionResponse.Usage.OutputTokens) * usedModelInfo.OutputPrice - addUsage(inputCost, outputCost, chatCompletionResponse.Usage.InputTokens, chatCompletionResponse.Usage.OutputTokens, model) + addUsage(c, inputCost, outputCost, chatCompletionResponse.Usage.InputTokens, chatCompletionResponse.Usage.OutputTokens, model) return chatCompletionResponse, nil } diff --git a/RequestGoogle.go b/RequestGoogle.go index 23d446a..f9f1b78 100644 --- a/RequestGoogle.go +++ b/RequestGoogle.go @@ -10,6 +10,7 @@ import ( "net/http" "github.com/edgedb/edgedb-go" + "github.com/gofiber/fiber/v2" ) type GoogleRequestMessage struct { @@ -51,20 +52,20 @@ type GoogleUsageMetadata struct { TotalTokenCount int32 `json:"totalTokenCount"` } -func addGoogleMessage(llm LLM, selected bool) edgedb.UUID { - Messages := getAllSelectedMessages() +func addGoogleMessage(c *fiber.Ctx, llm LLM, selected bool) edgedb.UUID { + Messages := getAllSelectedMessages(c) - chatCompletion, err := RequestGoogle(llm.Model.ModelID, Messages, float64(llm.Temperature), llm.Context) + chatCompletion, err := RequestGoogle(c, llm.Model.ModelID, Messages, float64(llm.Temperature), llm.Context) if err != nil { fmt.Println("Error fetching user profile") panic(err) } else if len(chatCompletion.Candidates) == 0 { fmt.Println("No response from Google") - id := insertBotMessage("No response from Google", selected, llm.ID) + id := insertBotMessage(c, "No response from Google", selected, llm.ID) return id } else { Content := chatCompletion.Candidates[0].Content.Parts[0].Text - id := insertBotMessage(Content, selected, llm.ID) + id := insertBotMessage(c, Content, selected, llm.ID) return id } } @@ -130,9 +131,9 @@ func TestGoogleKey(apiKey string) bool { return true } -func RequestGoogle(model string, messages []Message, temperature float64, context string) (GoogleChatCompletionResponse, error) { +func RequestGoogle(c *fiber.Ctx, model string, messages []Message, temperature float64, context string) (GoogleChatCompletionResponse, error) { var apiKey string - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` with filtered_keys := ( select Key { @@ -198,7 +199,7 @@ func RequestGoogle(model string, messages []Message, temperature float64, contex } var usedModelInfo ModelInfo - err = edgeClient.QuerySingle(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` SELECT ModelInfo { inputPrice, outputPrice @@ -212,7 +213,7 @@ func RequestGoogle(model string, messages []Message, temperature float64, contex var inputCost float32 = float32(chatCompletionResponse.UsageMetadata.PromptTokenCount) * usedModelInfo.InputPrice var outputCost float32 = float32(chatCompletionResponse.UsageMetadata.CandidatesTokenCount) * usedModelInfo.OutputPrice - addUsage(inputCost, outputCost, chatCompletionResponse.UsageMetadata.PromptTokenCount, chatCompletionResponse.UsageMetadata.CandidatesTokenCount, model) + addUsage(c, inputCost, outputCost, chatCompletionResponse.UsageMetadata.PromptTokenCount, chatCompletionResponse.UsageMetadata.CandidatesTokenCount, model) return chatCompletionResponse, nil } diff --git a/RequestGooseai.go b/RequestGooseai.go index 958852a..bb0ad21 100644 --- a/RequestGooseai.go +++ b/RequestGooseai.go @@ -11,6 +11,7 @@ import ( "net/http" "github.com/edgedb/edgedb-go" + "github.com/gofiber/fiber/v2" ) type GooseaiCompletionRequest struct { @@ -33,20 +34,20 @@ type GooseaiChoice struct { Index int `json:"index"` } -func addGooseaiMessage(llm LLM, selected bool) edgedb.UUID { - Messages := getAllSelectedMessages() +func addGooseaiMessage(c *fiber.Ctx, llm LLM, selected bool) edgedb.UUID { + Messages := getAllSelectedMessages(c) - chatCompletion, err := RequestGooseai(llm.Model.ModelID, Messages, float64(llm.Temperature)) + chatCompletion, err := RequestGooseai(c, llm.Model.ModelID, Messages, float64(llm.Temperature)) if err != nil { fmt.Println("Error fetching user profile") panic(err) } else if len(chatCompletion.Choices) == 0 { fmt.Println("No response from GooseAI") - id := insertBotMessage("No response from GooseAI", selected, llm.ID) + id := insertBotMessage(c, "No response from GooseAI", selected, llm.ID) return id } else { Content := chatCompletion.Choices[0].Text - id := insertBotMessage(Content, selected, llm.ID) + id := insertBotMessage(c, Content, selected, llm.ID) return id } } @@ -97,9 +98,9 @@ func TestGooseaiKey(apiKey string) bool { return true } -func RequestGooseai(model string, messages []Message, temperature float64) (GooseaiCompletionResponse, error) { +func RequestGooseai(c *fiber.Ctx, model string, messages []Message, temperature float64) (GooseaiCompletionResponse, error) { var apiKey string - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` with filtered_keys := ( select Key { @@ -157,7 +158,7 @@ func RequestGooseai(model string, messages []Message, temperature float64) (Goos return GooseaiCompletionResponse{}, fmt.Errorf("error unmarshaling JSON: %w", err) } - addUsage(0, 0, 0, 0, model) + addUsage(c, 0, 0, 0, 0, model) return chatCompletionResponse, nil } diff --git a/RequestGroq.go b/RequestGroq.go index 82a8315..f202b48 100644 --- a/RequestGroq.go +++ b/RequestGroq.go @@ -8,6 +8,7 @@ import ( "net/http" "github.com/edgedb/edgedb-go" + "github.com/gofiber/fiber/v2" ) type GroqChatCompletionRequest struct { @@ -37,20 +38,20 @@ type GroqChoice struct { Index int `json:"index"` } -func addGroqMessage(llm LLM, selected bool) edgedb.UUID { - Messages := getAllSelectedMessages() +func addGroqMessage(c *fiber.Ctx, llm LLM, selected bool) edgedb.UUID { + Messages := getAllSelectedMessages(c) - chatCompletion, err := RequestGroq(llm.Model.ModelID, Messages, float64(llm.Temperature), llm.Context) + chatCompletion, err := RequestGroq(c, llm.Model.ModelID, Messages, float64(llm.Temperature), llm.Context) if err != nil { fmt.Println("Error fetching user profile") panic(err) } else if len(chatCompletion.Choices) == 0 { fmt.Println("No response from Groq") - id := insertBotMessage("No response from Groq", selected, llm.ID) + id := insertBotMessage(c, "No response from Groq", selected, llm.ID) return id } else { Content := chatCompletion.Choices[0].Message.Content - id := insertBotMessage(Content, selected, llm.ID) + id := insertBotMessage(c, Content, selected, llm.ID) return id } } @@ -108,9 +109,9 @@ func TestGroqKey(apiKey string) bool { return true } -func RequestGroq(model string, messages []Message, temperature float64, context string) (GroqChatCompletionResponse, error) { +func RequestGroq(c *fiber.Ctx, model string, messages []Message, temperature float64, context string) (GroqChatCompletionResponse, error) { var apiKey string - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` with filtered_keys := ( select Key { @@ -163,7 +164,7 @@ func RequestGroq(model string, messages []Message, temperature float64, context } var usedModelInfo ModelInfo - edgeClient.QuerySingle(edgeCtx, ` + edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` SELECT ModelInfo { inputPrice, outputPrice @@ -174,7 +175,7 @@ func RequestGroq(model string, messages []Message, temperature float64, context var inputCost float32 = float32(chatCompletionResponse.Usage.PromptTokens) * usedModelInfo.InputPrice var outputCost float32 = float32(chatCompletionResponse.Usage.CompletionTokens) * usedModelInfo.OutputPrice - addUsage(inputCost, outputCost, chatCompletionResponse.Usage.PromptTokens, chatCompletionResponse.Usage.CompletionTokens, model) + addUsage(c, inputCost, outputCost, chatCompletionResponse.Usage.PromptTokens, chatCompletionResponse.Usage.CompletionTokens, model) return chatCompletionResponse, nil } diff --git a/RequestHuggingface.go b/RequestHuggingface.go index 8cbb367..014f16e 100644 --- a/RequestHuggingface.go +++ b/RequestHuggingface.go @@ -8,6 +8,7 @@ import ( "net/http" "github.com/edgedb/edgedb-go" + "github.com/gofiber/fiber/v2" ) type HuggingfaceChatCompletionRequest struct { @@ -37,25 +38,25 @@ type HuggingfaceChoice struct { Index int `json:"index"` } -func addHuggingfaceMessage(llm LLM, selected bool) edgedb.UUID { - Messages := getAllSelectedMessages() +func addHuggingfaceMessage(c *fiber.Ctx, llm LLM, selected bool) edgedb.UUID { + Messages := getAllSelectedMessages(c) - chatCompletion, err := RequestHuggingface(llm, Messages, float64(llm.Temperature)) + chatCompletion, err := RequestHuggingface(c, llm, Messages, float64(llm.Temperature)) if err != nil { fmt.Println("Error fetching user profile") panic(err) } else if len(chatCompletion.Choices) == 0 { fmt.Println("No response from Endpoint") - id := insertBotMessage("No response from Endpoint", selected, llm.ID) + id := insertBotMessage(c, "No response from Endpoint", selected, llm.ID) return id } else { Content := chatCompletion.Choices[0].Message.Content - id := insertBotMessage(Content, selected, llm.ID) + id := insertBotMessage(c, Content, selected, llm.ID) return id } } -func RequestHuggingface(llm LLM, messages []Message, temperature float64) (HuggingfaceChatCompletionResponse, error) { +func RequestHuggingface(c *fiber.Ctx, llm LLM, messages []Message, temperature float64) (HuggingfaceChatCompletionResponse, error) { url := llm.Endpoint.Endpoint requestBody := HuggingfaceChatCompletionRequest{ @@ -96,7 +97,7 @@ func RequestHuggingface(llm LLM, messages []Message, temperature float64) (Huggi return HuggingfaceChatCompletionResponse{}, fmt.Errorf("error unmarshaling JSON: %w", err) } - addUsage(0, 0, 0, 0, llm.Model.ModelID) + addUsage(c, 0, 0, 0, 0, llm.Model.ModelID) return chatCompletionResponse, nil } diff --git a/RequestMistral.go b/RequestMistral.go index 669b8aa..ce9168b 100644 --- a/RequestMistral.go +++ b/RequestMistral.go @@ -8,6 +8,7 @@ import ( "net/http" "github.com/edgedb/edgedb-go" + "github.com/gofiber/fiber/v2" ) type MistralChatCompletionRequest struct { @@ -36,19 +37,19 @@ type MistralChoice struct { Index int `json:"index"` } -func addMistralMessage(llm LLM, selected bool) edgedb.UUID { - Messages := getAllSelectedMessages() +func addMistralMessage(c *fiber.Ctx, llm LLM, selected bool) edgedb.UUID { + Messages := getAllSelectedMessages(c) - chatCompletion, err := RequestMistral(llm.Model.ModelID, Messages, float64(llm.Temperature), llm.Context) + chatCompletion, err := RequestMistral(c, llm.Model.ModelID, Messages, float64(llm.Temperature), llm.Context) if err != nil { fmt.Println("Error fetching user profile") panic(err) } else if len(chatCompletion.Choices) == 0 { - id := insertBotMessage("No response from Mistral", selected, llm.ID) + id := insertBotMessage(c, "No response from Mistral", selected, llm.ID) return id } else { Content := chatCompletion.Choices[0].Message.Content - id := insertBotMessage(Content, selected, llm.ID) + id := insertBotMessage(c, Content, selected, llm.ID) return id } } @@ -113,9 +114,9 @@ func TestMistralKey(apiKey string) bool { return true } -func RequestMistral(model string, messages []Message, temperature float64, context string) (MistralChatCompletionResponse, error) { +func RequestMistral(c *fiber.Ctx, model string, messages []Message, temperature float64, context string) (MistralChatCompletionResponse, error) { var apiKey string - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` with filtered_keys := ( select Key { @@ -169,7 +170,7 @@ func RequestMistral(model string, messages []Message, temperature float64, conte } var usedModelInfo ModelInfo - err = edgeClient.QuerySingle(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` SELECT ModelInfo { inputPrice, outputPrice @@ -187,7 +188,7 @@ func RequestMistral(model string, messages []Message, temperature float64, conte var inputCost float32 = float32(chatCompletionResponse.Usage.PromptTokens) * usedModelInfo.InputPrice var outputCost float32 = float32(chatCompletionResponse.Usage.CompletionTokens) * usedModelInfo.OutputPrice - addUsage(inputCost, outputCost, chatCompletionResponse.Usage.PromptTokens, chatCompletionResponse.Usage.CompletionTokens, model) + addUsage(c, inputCost, outputCost, chatCompletionResponse.Usage.PromptTokens, chatCompletionResponse.Usage.CompletionTokens, model) return chatCompletionResponse, nil } diff --git a/RequestOpenai.go b/RequestOpenai.go index 50cc523..4dfa4a4 100644 --- a/RequestOpenai.go +++ b/RequestOpenai.go @@ -8,6 +8,7 @@ import ( "net/http" "github.com/edgedb/edgedb-go" + "github.com/gofiber/fiber/v2" ) type OpenaiChatCompletionRequest struct { @@ -37,20 +38,20 @@ type OpenaiChoice struct { Index int `json:"index"` } -func addOpenaiMessage(llm LLM, selected bool) edgedb.UUID { - Messages := getAllSelectedMessages() +func addOpenaiMessage(c *fiber.Ctx, llm LLM, selected bool) edgedb.UUID { + Messages := getAllSelectedMessages(c) - chatCompletion, err := RequestOpenai(llm.Model.ModelID, Messages, float64(llm.Temperature), llm.Context) + chatCompletion, err := RequestOpenai(c, llm.Model.ModelID, Messages, float64(llm.Temperature), llm.Context) if err != nil { fmt.Println("Error fetching user profile") panic(err) } else if len(chatCompletion.Choices) == 0 { fmt.Println("No response from OpenAI") - id := insertBotMessage("No response from OpenAI", selected, llm.ID) + id := insertBotMessage(c, "No response from OpenAI", selected, llm.ID) return id } else { Content := chatCompletion.Choices[0].Message.Content - id := insertBotMessage(Content, selected, llm.ID) + id := insertBotMessage(c, Content, selected, llm.ID) return id } } @@ -108,9 +109,9 @@ func TestOpenaiKey(apiKey string) bool { return true } -func RequestOpenai(model string, messages []Message, temperature float64, context string) (OpenaiChatCompletionResponse, error) { +func RequestOpenai(c *fiber.Ctx, model string, messages []Message, temperature float64, context string) (OpenaiChatCompletionResponse, error) { var apiKey string - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` with filtered_keys := ( select Key { @@ -163,7 +164,7 @@ func RequestOpenai(model string, messages []Message, temperature float64, contex } var usedModelInfo ModelInfo - err = edgeClient.QuerySingle(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` SELECT ModelInfo { inputPrice, outputPrice @@ -177,7 +178,7 @@ func RequestOpenai(model string, messages []Message, temperature float64, contex var inputCost float32 = float32(chatCompletionResponse.Usage.PromptTokens) * usedModelInfo.InputPrice var outputCost float32 = float32(chatCompletionResponse.Usage.CompletionTokens) * usedModelInfo.OutputPrice - addUsage(inputCost, outputCost, chatCompletionResponse.Usage.PromptTokens, chatCompletionResponse.Usage.CompletionTokens, model) + addUsage(c, inputCost, outputCost, chatCompletionResponse.Usage.PromptTokens, chatCompletionResponse.Usage.CompletionTokens, model) return chatCompletionResponse, nil } diff --git a/Stripe.go b/Stripe.go index 8cb29d3..0bf9cbd 100644 --- a/Stripe.go +++ b/Stripe.go @@ -15,18 +15,18 @@ import ( ) func PricingTableHandler(c *fiber.Ctx) error { - return c.SendString(generatePricingTableChatHTML()) + return c.SendString(generatePricingTableChatHTML(c)) } -func generatePricingTableChatHTML() string { +func generatePricingTableChatHTML(c *fiber.Ctx) string { var result User - err := edgeClient.QuerySingle(edgeCtx, "SELECT global currentUser { stripe_id, email } LIMIT 1;", &result) + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, "SELECT global currentUser { stripe_id, email } LIMIT 1;", &result) if err != nil { fmt.Println("Error getting user") panic(err) } - clientSecretSession := CreateClientSecretSession() + clientSecretSession := CreateClientSecretSession(c) // TODO Replace by live API call stripeTable := ` @@ -83,9 +83,9 @@ func CreateNewStripeCustomer(name string, email string) string { return result.ID } -func IsCurrentUserSubscribed() bool { +func IsCurrentUserSubscribed(c *fiber.Ctx) bool { var user User - err := edgeClient.QuerySingle(edgeCtx, "SELECT global currentUser { stripe_id } LIMIT 1;", &user) + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, "SELECT global currentUser { stripe_id } LIMIT 1;", &user) if err != nil { fmt.Println("Error getting user") panic(err) @@ -102,10 +102,10 @@ func IsCurrentUserSubscribed() bool { return result.Subscriptions.Data[0].Plan.Product.ID == "prod_PnDjBBwvQN36cQ" && result.Subscriptions.Data[0].Plan.Active } -func IsCurrentUserLimiteReached() bool { +func IsCurrentUserLimiteReached(c *fiber.Ctx) bool { // Count the number of Usage for the current user var count int64 - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` WITH U := ( SELECT Usage @@ -120,9 +120,9 @@ func IsCurrentUserLimiteReached() bool { return count >= 500 } -func CreateClientSecretSession() string { +func CreateClientSecretSession(c *fiber.Ctx) string { var user User - err := edgeClient.QuerySingle(edgeCtx, "SELECT global currentUser { stripe_id } LIMIT 1;", &user) + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, "SELECT global currentUser { stripe_id } LIMIT 1;", &user) if err != nil { fmt.Println("Error getting user") panic(err) diff --git a/database.go b/database.go index 0902138..16db47a 100644 --- a/database.go +++ b/database.go @@ -9,11 +9,12 @@ import ( "time" "github.com/edgedb/edgedb-go" + "github.com/gofiber/fiber/v2" ) // So I have one client and one context for the database. All query use the same and it work well so far. var edgeCtx context.Context -var edgeClient *edgedb.Client +var edgeGlobalClient *edgedb.Client // I will not put a comment on all type, I think they are self-explaining. type Identity struct { @@ -128,19 +129,17 @@ func init() { } edgeCtx = ctx - edgeClient = client + edgeGlobalClient = client } -func checkIfLogin() bool { - var result User - err := edgeClient.QuerySingle(edgeCtx, "SELECT global currentUser LIMIT 1;", &result) - return err == nil +func checkIfLogin(c *fiber.Ctx) bool { + return c.Cookies("jade-edgedb-auth-token", "") != "" } -func insertArea() (edgedb.UUID, int64) { +func insertArea(c *fiber.Ctx) (edgedb.UUID, int64) { // Insert a new area. var inserted struct{ id edgedb.UUID } - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` WITH positionVar := count((SELECT Area FILTER .conversation = global currentConversation)) + 1 INSERT Area { @@ -154,7 +153,7 @@ func insertArea() (edgedb.UUID, int64) { } var positionSet struct{ position int64 } - err = edgeClient.QuerySingle(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` SELECT Area { position, } @@ -169,10 +168,10 @@ func insertArea() (edgedb.UUID, int64) { return inserted.id, positionSet.position } -func insertUserMessage(content string) edgedb.UUID { +func insertUserMessage(c *fiber.Ctx, content string) edgedb.UUID { // Insert a new user. var lastArea Area - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` SELECT Area { id } @@ -186,7 +185,7 @@ func insertUserMessage(content string) edgedb.UUID { } var inserted struct{ id edgedb.UUID } // TODO: Maybe remove that hard code LLM - err = edgeClient.QuerySingle(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` INSERT Message { role := $0, content := $1, @@ -208,9 +207,9 @@ func insertUserMessage(content string) edgedb.UUID { return inserted.id } -func insertBotMessage(content string, selected bool, llmUUID edgedb.UUID) edgedb.UUID { +func insertBotMessage(c *fiber.Ctx, content string, selected bool, llmUUID edgedb.UUID) edgedb.UUID { var lastArea Area - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` SELECT Area { id } @@ -224,7 +223,7 @@ func insertBotMessage(content string, selected bool, llmUUID edgedb.UUID) edgedb } var inserted struct{ id edgedb.UUID } - err = edgeClient.QuerySingle(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` INSERT Message { role := $0, content := $2, @@ -253,15 +252,15 @@ func insertBotMessage(content string, selected bool, llmUUID edgedb.UUID) edgedb return inserted.id } -func getAllSelectedMessages() []Message { +func getAllSelectedMessages(c *fiber.Ctx) []Message { // If no CurrentUser, return an empty array - if !checkIfLogin() { + if !checkIfLogin(c) { return []Message{} } var messages []Message - err := edgeClient.Query(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Query(edgeCtx, ` SELECT Message { id, selected, @@ -287,9 +286,9 @@ func getAllSelectedMessages() []Message { return messages } -func checkIfHaveKey() bool { +func checkIfHaveKey(c *fiber.Ctx) bool { var keys []Key - err := edgeClient.Query(edgeCtx, "SELECT global currentUser.setting.keys", &keys) + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Query(edgeCtx, "SELECT global currentUser.setting.keys", &keys) if err != nil { panic(err) } diff --git a/login.go b/login.go index da298ef..a3c8678 100644 --- a/login.go +++ b/login.go @@ -210,7 +210,7 @@ func handleCallbackSignup(c *fiber.Ctx) error { fmt.Println("Error parsing UUID") panic(err) } - err = edgeClient.QuerySingle(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` SELECT ext::auth::Identity { issuer } FILTER .id = $0 @@ -235,7 +235,7 @@ func handleCallbackSignup(c *fiber.Ctx) error { stripCustID := CreateNewStripeCustomer(providerName, providerEmail) - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` INSERT User { stripe_id := $0, email := $1, @@ -254,9 +254,7 @@ func handleCallbackSignup(c *fiber.Ctx) error { panic(err) } - edgeClient = edgeClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": tokenResponse.AuthToken}) - - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": tokenResponse.AuthToken}).Execute(edgeCtx, ` INSERT Conversation { name := 'Default', user := global currentUser, @@ -313,14 +311,10 @@ func handleCallback(c *fiber.Ctx) error { SameSite: "Strict", }) - edgeClient = edgeClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": tokenResponse.AuthToken}) - return c.Redirect("/", fiber.StatusPermanentRedirect) } func handleSignOut(c *fiber.Ctx) error { c.ClearCookie("jade-edgedb-auth-token") - edgeClient = edgeClient.WithoutGlobals("ext::auth::client_token") - return c.Redirect("/", fiber.StatusTemporaryRedirect) } diff --git a/main.go b/main.go index b4af8ab..32743b7 100644 --- a/main.go +++ b/main.go @@ -183,7 +183,7 @@ func addKeys(c *fiber.Ctx) error { } // Check if the company key already exists - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` select exists ( select global currentUser.setting.keys filter .company.name = "openai" @@ -195,7 +195,7 @@ func addKeys(c *fiber.Ctx) error { } if Exists { - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` UPDATE Key filter .company.name = $0 AND .key = $1 SET { key := $1, @@ -206,7 +206,7 @@ func addKeys(c *fiber.Ctx) error { panic(err) } } else { - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` WITH c := (SELECT Company FILTER .name = "openai" LIMIT 1) UPDATE global currentUser.setting @@ -233,7 +233,7 @@ func addKeys(c *fiber.Ctx) error { } // Check if the company key already exists - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` select exists ( select global currentUser.setting.keys filter .company.name = "anthropic" @@ -245,7 +245,7 @@ func addKeys(c *fiber.Ctx) error { } if Exists { - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` UPDATE Key filter .company.name = "anthropic" AND .key = $0 SET { key := $0, @@ -256,7 +256,7 @@ func addKeys(c *fiber.Ctx) error { panic(err) } } else { - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` WITH c := (SELECT Company FILTER .name = "anthropic" LIMIT 1) UPDATE global currentUser.setting @@ -283,7 +283,7 @@ func addKeys(c *fiber.Ctx) error { } // Check if the company key already exists - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` select exists ( select global currentUser.setting.keys filter .company.name = "mistral" @@ -295,7 +295,7 @@ func addKeys(c *fiber.Ctx) error { } if Exists { - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` UPDATE Key filter .company.name = "mistral" AND .key = $0 SET { key := $0, @@ -306,7 +306,7 @@ func addKeys(c *fiber.Ctx) error { panic(err) } } else { - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` WITH c := (SELECT Company FILTER .name = "mistral" LIMIT 1) UPDATE global currentUser.setting @@ -333,7 +333,7 @@ func addKeys(c *fiber.Ctx) error { } // Check if the company key already exists - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` select exists ( select global currentUser.setting.keys filter .company.name = "groq" @@ -345,7 +345,7 @@ func addKeys(c *fiber.Ctx) error { } if Exists { - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` UPDATE Key filter .company.name = "groq" AND .key = $0 SET { key := $0, @@ -356,7 +356,7 @@ func addKeys(c *fiber.Ctx) error { panic(err) } } else { - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` WITH c := (SELECT Company FILTER .name = "groq" LIMIT 1) UPDATE global currentUser.setting @@ -383,7 +383,7 @@ func addKeys(c *fiber.Ctx) error { } // Check if the company key already exists - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` select exists ( select global currentUser.setting.keys filter .company.name = "gooseai" @@ -395,7 +395,7 @@ func addKeys(c *fiber.Ctx) error { } if Exists { - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` UPDATE Key filter .company.name = "gooseai" AND .key = $0 SET { key := $0, @@ -406,7 +406,7 @@ func addKeys(c *fiber.Ctx) error { panic(err) } } else { - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` WITH c := (SELECT Company FILTER .name = "gooseai" LIMIT 1) UPDATE global currentUser.setting @@ -433,7 +433,7 @@ func addKeys(c *fiber.Ctx) error { } // Check if the company key already exists - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` select exists ( select global currentUser.setting.keys filter .company.name = "google" @@ -445,7 +445,7 @@ func addKeys(c *fiber.Ctx) error { } if Exists { - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` UPDATE Key filter .company.name = "google" AND .key = $0 SET { key := $0, @@ -456,7 +456,7 @@ func addKeys(c *fiber.Ctx) error { panic(err) } } else { - err = edgeClient.Execute(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Execute(edgeCtx, ` WITH c := (SELECT Company FILTER .name = "google" LIMIT 1) UPDATE global currentUser.setting diff --git a/utils.go b/utils.go index 94a6761..688de3e 100644 --- a/utils.go +++ b/utils.go @@ -8,6 +8,7 @@ import ( "fmt" "regexp" + "github.com/gofiber/fiber/v2" "github.com/yuin/goldmark" highlighting "github.com/yuin/goldmark-highlighting" "github.com/yuin/goldmark/parser" @@ -77,8 +78,8 @@ func addCodeHeader(htmlContent string, languages []string) string { return updatedHTML } -func getExistingKeys() (bool, bool, bool, bool, bool, bool) { - if edgeClient == nil { +func getExistingKeys(c *fiber.Ctx) (bool, bool, bool, bool, bool, bool) { + if edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}) == nil { return false, false, false, false, false, false } @@ -91,7 +92,7 @@ func getExistingKeys() (bool, bool, bool, bool, bool, bool) { googleExists bool ) - err := edgeClient.QuerySingle(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` select exists ( select global currentUser.setting.keys filter .company.name = "openai" @@ -102,7 +103,7 @@ func getExistingKeys() (bool, bool, bool, bool, bool, bool) { panic(err) } - err = edgeClient.QuerySingle(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` select exists ( select global currentUser.setting.keys filter .company.name = "anthropic" @@ -113,7 +114,7 @@ func getExistingKeys() (bool, bool, bool, bool, bool, bool) { panic(err) } - err = edgeClient.QuerySingle(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` select exists ( select global currentUser.setting.keys filter .company.name = "mistral" @@ -124,7 +125,7 @@ func getExistingKeys() (bool, bool, bool, bool, bool, bool) { panic(err) } - err = edgeClient.QuerySingle(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` select exists ( select global currentUser.setting.keys filter .company.name = "groq" @@ -135,7 +136,7 @@ func getExistingKeys() (bool, bool, bool, bool, bool, bool) { panic(err) } - err = edgeClient.QuerySingle(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` select exists ( select global currentUser.setting.keys filter .company.name = "gooseai" @@ -146,7 +147,7 @@ func getExistingKeys() (bool, bool, bool, bool, bool, bool) { panic(err) } - err = edgeClient.QuerySingle(edgeCtx, ` + err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).QuerySingle(edgeCtx, ` select exists ( select global currentUser.setting.keys filter .company.name = "google" @@ -207,10 +208,10 @@ func Message2RequestMessage(messages []Message, context string) []RequestMessage } } -func GetAvailableModels() []ModelInfo { +func GetAvailableModels(c *fiber.Ctx) []ModelInfo { // TODO Filter if key is not available var models []ModelInfo - err := edgeClient.Query(edgeCtx, ` + err := edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token", "")}).Query(edgeCtx, ` SELECT ModelInfo { modelID, name,