Files
sproutclaw-web/backend/internal/handlers/models.go
2026-06-13 20:16:09 +08:00

78 lines
2.1 KiB
Go

package handlers
import (
"encoding/json"
"net/http"
"os"
"github.com/gin-gonic/gin"
"sproutclaw-web/internal/config"
"sproutclaw-web/internal/models"
"sproutclaw-web/internal/rpc"
)
// RegisterModels registers model-related routes.
func RegisterModels(r *gin.RouterGroup, cfg *config.Config, piClient *rpc.Client) {
r.GET("/models", handleGetModels(cfg, piClient))
r.POST("/model", handleSetModel(piClient))
r.POST("/thinking", handleSetThinking(piClient))
}
func handleGetModels(cfg *config.Config, piClient *rpc.Client) gin.HandlerFunc {
return func(c *gin.Context) {
resp, err := piClient.SendCmd(models.RPCCommand{Type: "list_models"})
if err != nil {
// fallback: read models.json
data, ferr := os.ReadFile(cfg.ModelsConfigFile)
if ferr != nil {
c.JSON(http.StatusOK, models.ModelsResponse{Models: []models.ModelEntry{}})
return
}
var raw any
_ = json.Unmarshal(data, &raw)
c.JSON(http.StatusOK, raw)
return
}
c.JSON(http.StatusOK, jsonRaw(resp.Result))
}
}
func handleSetModel(piClient *rpc.Client) gin.HandlerFunc {
return func(c *gin.Context) {
var req models.SetModelRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, models.ErrorResponse{Error: err.Error()})
return
}
resp, err := piClient.SendCmd(models.RPCCommand{
Type: "set_model",
Provider: req.Provider,
ModelID: req.ModelID,
})
if err != nil {
c.JSON(http.StatusInternalServerError, models.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, jsonRaw(resp.Result))
}
}
func handleSetThinking(piClient *rpc.Client) gin.HandlerFunc {
return func(c *gin.Context) {
var req models.SetThinkingRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, models.ErrorResponse{Error: err.Error()})
return
}
resp, err := piClient.SendCmd(models.RPCCommand{
Type: "set_thinking",
Budget: req.Budget,
})
if err != nil {
c.JSON(http.StatusInternalServerError, models.ErrorResponse{Error: err.Error()})
return
}
c.JSON(http.StatusOK, jsonRaw(resp.Result))
}
}