Skip to content

Commit

Permalink
feat: create new chat conversations
Browse files Browse the repository at this point in the history
  • Loading branch information
catpaladin committed Jul 10, 2024
1 parent 875cf06 commit 1c3e365
Show file tree
Hide file tree
Showing 7 changed files with 104 additions and 33 deletions.
20 changes: 10 additions & 10 deletions app/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,11 @@ func insertMessage(conversationID int, human, response, platform, model string)
}

func getMessagesByConversationID(conversationID int) ([]Message, error) {
rows, err := db.Query("SELECT id, conversation_id, human, response, platform, model FROM messages WHERE conversation_id = ?", conversationID)
rows, err := db.Query(`
SELECT id, conversation_id, COALESCE(human, ''), COALESCE(response, ''), platform, model
FROM messages
WHERE conversation_id = ?
ORDER BY id ASC`, conversationID)
if err != nil {
return nil, err
}
Expand All @@ -59,6 +63,7 @@ func getMessagesByConversationID(conversationID int) ([]Message, error) {
for rows.Next() {
var msg Message
if err := rows.Scan(&msg.ID, &msg.ConversationID, &msg.Human, &msg.Response, &msg.Platform, &msg.Model); err != nil {
log.Printf("Error scanning row: %v", err)
return nil, err
}
messages = append(messages, msg)
Expand All @@ -67,8 +72,8 @@ func getMessagesByConversationID(conversationID int) ([]Message, error) {
}

func getAllConversations() ([]Conversation, error) {
query := `
SELECT c.id, m.human, m.response
rows, err := db.Query(`
SELECT c.id, COALESCE(m.human, ''), COALESCE(m.response, '')
FROM conversations c
LEFT JOIN messages m ON m.id = (
SELECT id FROM messages
Expand All @@ -77,10 +82,9 @@ func getAllConversations() ([]Conversation, error) {
LIMIT 1
)
ORDER BY c.id
`
rows, err := db.Query(query)
`)
if err != nil {
log.Printf("Error executing query %s: %v", query, err)
log.Printf("Error executing query: %v", err)
return nil, err
}
defer rows.Close()
Expand All @@ -94,10 +98,6 @@ func getAllConversations() ([]Conversation, error) {
}
conversations = append(conversations, conv)
}
if err = rows.Err(); err != nil {
log.Printf("Error iterating over rows: %v", err)
return nil, err
}
return conversations, nil
}

Expand Down
31 changes: 30 additions & 1 deletion app/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,23 @@ type ChatMessage struct {
Model string
}

func createConversation(c *gin.Context) {
conversationID, err := createNewConversation()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create a new conversation"})
return
}

appState := state.GetState()
appState.SetConversationID(conversationID)

c.HTML(http.StatusOK, "chat.html", gin.H{
"ChatMessages": []ChatMessage{},
"Platform": appState.GetPlatform(),
"Model": appState.GetModel(),
})
}

func getMessagesFromDB(c *gin.Context) {
conversationID, err := strconv.Atoi(c.Param("id"))
if err != nil {
Expand Down Expand Up @@ -50,7 +67,7 @@ func getMessagesFromDB(c *gin.Context) {
return
}

parsed = strings.ReplaceAll(parsed, "<pre>", "<div class='card bg-base-100 shadow-xl'><div class='card-body'><pre>")
parsed = strings.ReplaceAll(parsed, "<pre>", "<div class='card bg-base-100 shadow-xl'><div class='card-body overflow-x-auto'><pre>")
parsed = strings.ReplaceAll(parsed, "</pre>", "</pre></div></div>")

chatMessages = append(chatMessages, ChatMessage{
Expand All @@ -77,3 +94,15 @@ func getAllMessagesFromDB(c *gin.Context) {
"Conversations": conversations,
})
}

func getAllConversationsHandler(c *gin.Context) {
conversations, err := getAllConversations()
if err != nil {
log.Print(err)
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.HTML(http.StatusOK, "sidebar.html", gin.H{
"Conversations": conversations,
})
}
42 changes: 32 additions & 10 deletions app/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,21 +83,43 @@ func (mc *ModelConfig) runModel(ctx context.Context) gin.HandlerFunc {
return
}

// parse markdown
parsed, err := parser.ParseMD(response)
// Retrieve all messages again to update the chat window
messages, err := getMessagesByConversationID(conversationID)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve messages"})
return
}

parsed = strings.ReplaceAll(parsed, "<pre>", "<div class='card bg-base-100 shadow-xl'><div class='card-body'><pre>")
parsed = strings.ReplaceAll(parsed, "</pre>", "</pre></div></div>")
var chatMessages []ChatMessage
for _, msg := range messages {
parsedHuman, _ := parser.ParseMD(msg.Human)
parsedResponse, _ := parser.ParseMD(msg.Response)
parsedResponse = strings.ReplaceAll(parsedResponse, "<pre>", "<div class='card bg-base-100 shadow-xl'><div class='card-body overflow-x-auto'><pre>")
parsedResponse = strings.ReplaceAll(parsedResponse, "</pre>", "</pre></div></div>")
chatMessages = append(chatMessages, ChatMessage{
Human: template.HTML(parsedHuman),
Response: template.HTML(parsedResponse),
Platform: msg.Platform,
Model: msg.Model,
})
}

// Fetch updated list of conversations
conversations, err := getAllConversations()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve conversations"})
return
}

c.HTML(http.StatusOK, "sidebar.html", gin.H{
"Conversations": conversations,
})

c.HTML(http.StatusOK, "chat.html", gin.H{
"Human": template.HTML(message),
"Response": template.HTML(parsed),
"Platform": platform,
"Model": modelID,
"ConversationID": conversationID,
"ChatMessages": chatMessages,
"Platform": platform,
"Model": modelID,
})

}
}
1 change: 1 addition & 0 deletions app/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ func (mc *ModelConfig) Serve(ctx context.Context) {
router.GET("/model", getModelsByPlatform(ctx, mc.Region))
router.POST("/select-model", selectModel)
router.POST("/run", mc.runModel(ctx))
router.POST("/new-conversation", createConversation)

if err := router.Run(":31000"); err != nil {
log.Fatal(err)
Expand Down
8 changes: 4 additions & 4 deletions templates/chat.html
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
{{define "chat.html"}}
{{range .ChatMessages}}
{{if .Human}}
<div class="chat chat-start">
<div class="chat chat-start max-w-3xl w-full mb-4 p-4">
<div class="chat-image avatar">
<div class="w-10 rounded-full">
<img src="https://api.dicebear.com/9.x/thumbs/svg?seed=Jasmine" />
</div>
</div>
<div class="chat-header">You</div>
<div class="chat-bubble">{{.Human}}</div>
<div class="chat-bubble" style="max-width: 100%; word-break: break-word;">{{.Human}}</div>
</div>
{{end}}
{{if .Response}}
<div class="chat chat-end">
<div class="chat chat-end max-w-3xl w-full mb-4 p-4">
<div class="chat-image avatar">
<div class="w-10 rounded-full">
<img src="https://api.dicebear.com/9.x/bottts/svg?seed=Leo" />
</div>
</div>
<div class="chat-header">JennAI</div>
<div class="chat-bubble">{{.Response}}</div>
<div class="chat-bubble" style="max-width: 100%; word-break: break-word;">{{.Response}}</div>
<div class="chat-footer opacity-50">{{.Platform}} - {{.Model}}</div>
</div>
{{end}}
Expand Down
33 changes: 26 additions & 7 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,25 @@

<div class="flex h-screen">
<!-- Sidebar -->
<div class="w-64 bg-gray-900 p-4 flex flex-col" hx-get="/messages" hx-trigger="load" hx-target="#sidebar-messages" hx-swap="innerHTML">
<div class="text-white text-xl mb-4">{{.Message}}</div>
<div
class="w-64 bg-gray-900 p-4 flex flex-col h-screen"
hx-get="/messages"
hx-trigger="load"
hx-target="#sidebar-messages"
hx-swap="innerHTML"
>
<div class="flex justify-between items-center text-white text-xl mb-4 space-x-4">
<span>{{.Message}}</span>
<button
class="btn btn-square btn-outline right-4"
hx-post="/new-conversation"
hx-trigger="click"
hx-target="#messages"
hx-swap="innerHTML"
>
<i class="fa-regular fa-comment-dots"></i>
</button>
</div>
<div id="sidebar-messages">
<!-- Messages will be loaded here -->
</div>
Expand All @@ -53,11 +70,13 @@

<!-- Right Card -->
<div class="card rounded-box grid h-20 flex-grow place-items-center">
<label class="flex cursor-pointer gap-2">
<span class="label-text">Current</span>
<input type="checkbox" value="coffee" class="toggle theme-controller" />
<span class="label-text">Coffee</span>
</label>
<div class="flex flex-row items-center space-x-4">
<label class="flex cursor-pointer gap-2">
<span class="label-text">Current</span>
<input type="checkbox" value="coffee" class="toggle theme-controller" />
<span class="label-text">Coffee</span>
</label>
</div>
</div>
</div>

Expand Down
2 changes: 1 addition & 1 deletion templates/prompt.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
id="submitBtn"
hx-post="/run"
hx-trigger="click, keyup[ctrlKey&&key=='Enter'] from:textarea"
hx-swap="beforeend"
hx-swap="innerHTML"
hx-target="#messages"
class="absolute top-1/2 right-4 transform -translate-y-1/2 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full focus:outline-none focus:ring-2 focus:ring-blue-500"
>
Expand Down

0 comments on commit 1c3e365

Please sign in to comment.