Create handler/chat.go
Browse files- internal/handler/chat.go +48 -0
internal/handler/chat.go
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package handler
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"net/http"
|
| 5 |
+
|
| 6 |
+
"github.com/gin-gonic/gin"
|
| 7 |
+
"zencoder-2api/internal/model"
|
| 8 |
+
"zencoder-2api/internal/service"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
type ChatHandler struct {
|
| 12 |
+
svc *service.APIService
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
func NewChatHandler() *ChatHandler {
|
| 16 |
+
return &ChatHandler{svc: service.NewAPIService()}
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
func (h *ChatHandler) ChatCompletions(c *gin.Context) {
|
| 20 |
+
var req model.ChatCompletionRequest
|
| 21 |
+
if err := c.ShouldBindJSON(&req); err != nil {
|
| 22 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
| 23 |
+
return
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
if req.Stream {
|
| 27 |
+
h.handleStream(c, &req)
|
| 28 |
+
return
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
resp, err := h.svc.Chat(&req)
|
| 32 |
+
if err != nil {
|
| 33 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
| 34 |
+
return
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
c.JSON(http.StatusOK, resp)
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
func (h *ChatHandler) handleStream(c *gin.Context, req *model.ChatCompletionRequest) {
|
| 41 |
+
c.Writer.Header().Set("Content-Type", "text/event-stream")
|
| 42 |
+
c.Writer.Header().Set("Cache-Control", "no-cache")
|
| 43 |
+
c.Writer.Header().Set("Connection", "keep-alive")
|
| 44 |
+
|
| 45 |
+
if err := h.svc.ChatStream(req, c.Writer); err != nil {
|
| 46 |
+
c.SSEvent("error", err.Error())
|
| 47 |
+
}
|
| 48 |
+
}
|