71 lines
1.7 KiB
Go
71 lines
1.7 KiB
Go
package handler
|
|
|
|
import (
|
|
"io"
|
|
"net/http"
|
|
"resume-platform/internal/service/chat"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// ChatHandler 聊天对话处理器,基于文档向量库进行问答
|
|
type ChatHandler struct {
|
|
chatService chat.ChatService
|
|
}
|
|
|
|
// NewChatHandler 创建聊天处理器实例
|
|
// @param chatService 聊天服务层
|
|
// @return *ChatHandler 处理器实例
|
|
// @author sunct
|
|
func NewChatHandler(chatService chat.ChatService) *ChatHandler {
|
|
return &ChatHandler{chatService: chatService}
|
|
}
|
|
|
|
// Chat 流式对话接口,以 SSE 方式返回 AI 回答
|
|
// @param c Gin 上下文
|
|
// @author sunct
|
|
func (h *ChatHandler) Chat(c *gin.Context) {
|
|
userID := c.Query("user_id")
|
|
if userID == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "user_id is required"})
|
|
return
|
|
}
|
|
|
|
var request struct {
|
|
Question string `json:"question"`
|
|
}
|
|
if err := c.ShouldBindJSON(&request); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
|
|
return
|
|
}
|
|
|
|
c.Stream(func(w io.Writer) bool {
|
|
answer, err := h.chatService.Chat(c.Request.Context(), userID, request.Question)
|
|
if err != nil {
|
|
c.SSEvent("error", gin.H{"message": err.Error()})
|
|
return false
|
|
}
|
|
|
|
c.SSEvent("message", answer)
|
|
return true
|
|
})
|
|
}
|
|
|
|
// GetChatHistory 获取用户聊天历史记录接口
|
|
// @param c Gin 上下文
|
|
// @author sunct
|
|
func (h *ChatHandler) GetChatHistory(c *gin.Context) {
|
|
userID := c.Query("user_id")
|
|
if userID == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "user_id is required"})
|
|
return
|
|
}
|
|
|
|
history, err := h.chatService.GetChatHistory(c.Request.Context(), userID)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, history)
|
|
} |