2024-02-10 20:37:03 +00:00
|
|
|
package fiberContext
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/gofiber/fiber/v2"
|
2024-07-10 13:28:39 +00:00
|
|
|
"github.com/mudler/LocalAI/core/config"
|
|
|
|
"github.com/mudler/LocalAI/core/services"
|
2024-06-23 08:24:36 +00:00
|
|
|
"github.com/mudler/LocalAI/pkg/model"
|
2024-02-10 20:37:03 +00:00
|
|
|
"github.com/rs/zerolog/log"
|
|
|
|
)
|
|
|
|
|
|
|
|
// ModelFromContext returns the model from the context
|
|
|
|
// If no model is specified, it will take the first available
|
|
|
|
// Takes a model string as input which should be the one received from the user request.
|
|
|
|
// It returns the model name resolved from the context and an error if any.
|
2024-07-10 13:28:39 +00:00
|
|
|
func ModelFromContext(ctx *fiber.Ctx, cl *config.BackendConfigLoader, loader *model.ModelLoader, modelInput string, firstModel bool) (string, error) {
|
2024-04-17 21:33:49 +00:00
|
|
|
if ctx.Params("model") != "" {
|
|
|
|
modelInput = ctx.Params("model")
|
2024-02-10 20:37:03 +00:00
|
|
|
}
|
2024-10-02 18:20:50 +00:00
|
|
|
if ctx.Query("model") != "" {
|
|
|
|
modelInput = ctx.Query("model")
|
|
|
|
}
|
2024-02-10 20:37:03 +00:00
|
|
|
// Set model from bearer token, if available
|
2024-10-01 18:55:46 +00:00
|
|
|
bearer := strings.TrimLeft(ctx.Get("authorization"), "Bear ") // Reduced duplicate characters of Bearer
|
2024-04-17 21:33:49 +00:00
|
|
|
bearerExists := bearer != "" && loader.ExistsInModelPath(bearer)
|
2024-02-10 20:37:03 +00:00
|
|
|
|
|
|
|
// If no model was specified, take the first available
|
|
|
|
if modelInput == "" && !bearerExists && firstModel {
|
2024-10-01 18:55:46 +00:00
|
|
|
models, _ := services.ListModels(cl, loader, config.NoFilterFn, services.SKIP_IF_CONFIGURED)
|
2024-02-10 20:37:03 +00:00
|
|
|
if len(models) > 0 {
|
|
|
|
modelInput = models[0]
|
2024-04-17 21:33:49 +00:00
|
|
|
log.Debug().Msgf("No model specified, using: %s", modelInput)
|
2024-02-10 20:37:03 +00:00
|
|
|
} else {
|
2024-04-17 21:33:49 +00:00
|
|
|
log.Debug().Msgf("No model specified, returning error")
|
|
|
|
return "", fmt.Errorf("no model specified")
|
2024-02-10 20:37:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If a model is found in bearer token takes precedence
|
|
|
|
if bearerExists {
|
2024-04-17 21:33:49 +00:00
|
|
|
log.Debug().Msgf("Using model from bearer token: %s", bearer)
|
2024-02-10 20:37:03 +00:00
|
|
|
modelInput = bearer
|
|
|
|
}
|
|
|
|
return modelInput, nil
|
|
|
|
}
|