2024-02-10 20:37:03 +00:00
|
|
|
package fiberContext
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/go-skynet/LocalAI/pkg/model"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
|
|
"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-04-17 21:33:49 +00:00
|
|
|
func ModelFromContext(ctx *fiber.Ctx, loader *model.ModelLoader, modelInput string, firstModel bool) (string, error) {
|
|
|
|
if ctx.Params("model") != "" {
|
|
|
|
modelInput = ctx.Params("model")
|
2024-02-10 20:37:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Set model from bearer token, if available
|
2024-04-17 21:33:49 +00:00
|
|
|
bearer := strings.TrimLeft(ctx.Get("authorization"), "Bearer ")
|
|
|
|
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-04-17 21:33:49 +00:00
|
|
|
models, _ := loader.ListModels()
|
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
|
|
|
|
}
|