Skip to content

Commit

Permalink
fix: implement chat response processing and correct webhook URL
Browse files Browse the repository at this point in the history
  • Loading branch information
aliraza556 committed Dec 16, 2024
1 parent feaaa94 commit 109f730
Showing 1 changed file with 54 additions and 4 deletions.
58 changes: 54 additions & 4 deletions handlers/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ import (
"bytes"
"encoding/json"
"fmt"
"github.com/rs/xid"
"github.com/stakwork/sphinx-tribes/websocket"
"io"
"log"
"net/http"
"os"
"time"

"github.com/rs/xid"
"github.com/stakwork/sphinx-tribes/websocket"

"github.com/go-chi/chi"
"github.com/stakwork/sphinx-tribes/db"
)
Expand Down Expand Up @@ -192,7 +193,7 @@ func (ch *ChatHandler) SendMessage(w http.ResponseWriter, r *http.Request) {
"history": messageHistory,
"contextTags": context,
"sourceWebsocketId": request.SourceWebsocketID,
"webhook_url": fmt.Sprintf("%s/hivechat/process", os.Getenv("HOST")),
"webhook_url": fmt.Sprintf("%s/hivechat/response", os.Getenv("HOST")),
},
},
},
Expand Down Expand Up @@ -298,9 +299,58 @@ func (ch *ChatHandler) GetChatHistory(w http.ResponseWriter, r *http.Request) {
}

func (ch *ChatHandler) ProcessChatResponse(w http.ResponseWriter, r *http.Request) {
var request struct {
ChatID string `json:"chatId"`
MessageID string `json:"messageId"`
Response string `json:"response"`
SourceWebsocketID string `json:"sourceWebsocketId"`
}

if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(ChatResponse{
Success: false,
Message: "Invalid request body",
})
return
}

message := &db.ChatMessage{
ID: request.MessageID,
ChatID: request.ChatID,
Message: request.Response,
Role: "assistant",
Timestamp: time.Now(),
Status: "sent",
Source: "agent",
}

createdMessage, err := ch.db.AddChatMessage(message)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(ChatResponse{
Success: false,
Message: fmt.Sprintf("Failed to save response message: %v", err),
})
return
}

wsMessage := websocket.TicketMessage{
BroadcastType: "direct",
SourceSessionID: request.SourceWebsocketID,
Message: "Response received",
Action: "message",
ChatMessage: createdMessage,
}

if err := websocket.WebsocketPool.SendTicketMessage(wsMessage); err != nil {
log.Printf("Failed to send websocket message: %v", err)
}

w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(ChatResponse{
Success: true,
Message: "Stubbed out - process chat response",
Message: "Response processed successfully",
Data: createdMessage,
})
}

0 comments on commit 109f730

Please sign in to comment.