mirror of
https://github.com/mudler/LocalAI.git
synced 2024-06-07 19:40:48 +00:00
c4f958e11b
* start breaking up the giant channel refactor now that it's better understood - easier to merge bites Signed-off-by: Dave Lee <dave@gray101.com> * add concurrency and base64 back in, along with new base64 tests. Signed-off-by: Dave Lee <dave@gray101.com> * Automatic rename of whisper.go's Result to TranscriptResult Signed-off-by: Dave Lee <dave@gray101.com> * remove pkg/concurrency - significant changes coming in split 2 Signed-off-by: Dave Lee <dave@gray101.com> * fix comments Signed-off-by: Dave Lee <dave@gray101.com> * add list_model service as another low-risk service to get it out of the way Signed-off-by: Dave Lee <dave@gray101.com> * split backend config loader into seperate file from the actual config struct. No changes yet, just reduce cognative load with smaller files of logical blocks Signed-off-by: Dave Lee <dave@gray101.com> * rename state.go ==> application.go Signed-off-by: Dave Lee <dave@gray101.com> * fix lost import? Signed-off-by: Dave Lee <dave@gray101.com> --------- Signed-off-by: Dave Lee <dave@gray101.com>
182 lines
5.1 KiB
Go
182 lines
5.1 KiB
Go
package http
|
|
|
|
import (
|
|
"errors"
|
|
"strings"
|
|
|
|
"github.com/go-skynet/LocalAI/pkg/utils"
|
|
|
|
"github.com/go-skynet/LocalAI/core/http/endpoints/localai"
|
|
"github.com/go-skynet/LocalAI/core/http/endpoints/openai"
|
|
"github.com/go-skynet/LocalAI/core/http/routes"
|
|
|
|
"github.com/go-skynet/LocalAI/core/config"
|
|
"github.com/go-skynet/LocalAI/core/schema"
|
|
"github.com/go-skynet/LocalAI/core/services"
|
|
"github.com/go-skynet/LocalAI/pkg/model"
|
|
|
|
"github.com/gofiber/contrib/fiberzerolog"
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/gofiber/fiber/v2/middleware/cors"
|
|
"github.com/gofiber/fiber/v2/middleware/recover"
|
|
|
|
// swagger handler
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
func readAuthHeader(c *fiber.Ctx) string {
|
|
authHeader := c.Get("Authorization")
|
|
|
|
// elevenlabs
|
|
xApiKey := c.Get("xi-api-key")
|
|
if xApiKey != "" {
|
|
authHeader = "Bearer " + xApiKey
|
|
}
|
|
|
|
// anthropic
|
|
xApiKey = c.Get("x-api-key")
|
|
if xApiKey != "" {
|
|
authHeader = "Bearer " + xApiKey
|
|
}
|
|
|
|
return authHeader
|
|
}
|
|
|
|
// @title LocalAI API
|
|
// @version 2.0.0
|
|
// @description The LocalAI Rest API.
|
|
// @termsOfService
|
|
// @contact.name LocalAI
|
|
// @contact.url https://localai.io
|
|
// @license.name MIT
|
|
// @license.url https://raw.githubusercontent.com/mudler/LocalAI/master/LICENSE
|
|
// @BasePath /
|
|
// @securityDefinitions.apikey BearerAuth
|
|
// @in header
|
|
// @name Authorization
|
|
|
|
func App(cl *config.BackendConfigLoader, ml *model.ModelLoader, appConfig *config.ApplicationConfig) (*fiber.App, error) {
|
|
// Return errors as JSON responses
|
|
app := fiber.New(fiber.Config{
|
|
Views: renderEngine(),
|
|
BodyLimit: appConfig.UploadLimitMB * 1024 * 1024, // this is the default limit of 4MB
|
|
// We disable the Fiber startup message as it does not conform to structured logging.
|
|
// We register a startup log line with connection information in the OnListen hook to keep things user friendly though
|
|
DisableStartupMessage: true,
|
|
// Override default error handler
|
|
ErrorHandler: func(ctx *fiber.Ctx, err error) error {
|
|
// Status code defaults to 500
|
|
code := fiber.StatusInternalServerError
|
|
|
|
// Retrieve the custom status code if it's a *fiber.Error
|
|
var e *fiber.Error
|
|
if errors.As(err, &e) {
|
|
code = e.Code
|
|
}
|
|
|
|
// Send custom error page
|
|
return ctx.Status(code).JSON(
|
|
schema.ErrorResponse{
|
|
Error: &schema.APIError{Message: err.Error(), Code: code},
|
|
},
|
|
)
|
|
},
|
|
})
|
|
|
|
app.Hooks().OnListen(func(listenData fiber.ListenData) error {
|
|
scheme := "http"
|
|
if listenData.TLS {
|
|
scheme = "https"
|
|
}
|
|
log.Info().Str("endpoint", scheme+"://"+listenData.Host+":"+listenData.Port).Msg("LocalAI API is listening! Please connect to the endpoint for API documentation.")
|
|
return nil
|
|
})
|
|
|
|
// Have Fiber use zerolog like the rest of the application rather than it's built-in logger
|
|
logger := log.Logger
|
|
app.Use(fiberzerolog.New(fiberzerolog.Config{
|
|
Logger: &logger,
|
|
}))
|
|
|
|
// Default middleware config
|
|
|
|
if !appConfig.Debug {
|
|
app.Use(recover.New())
|
|
}
|
|
|
|
metricsService, err := services.NewLocalAIMetricsService()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if metricsService != nil {
|
|
app.Use(localai.LocalAIMetricsAPIMiddleware(metricsService))
|
|
app.Hooks().OnShutdown(func() error {
|
|
return metricsService.Shutdown()
|
|
})
|
|
}
|
|
|
|
// Auth middleware checking if API key is valid. If no API key is set, no auth is required.
|
|
auth := func(c *fiber.Ctx) error {
|
|
if len(appConfig.ApiKeys) == 0 {
|
|
return c.Next()
|
|
}
|
|
|
|
if len(appConfig.ApiKeys) == 0 {
|
|
return c.Next()
|
|
}
|
|
|
|
authHeader := readAuthHeader(c)
|
|
if authHeader == "" {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Authorization header missing"})
|
|
}
|
|
|
|
// If it's a bearer token
|
|
authHeaderParts := strings.Split(authHeader, " ")
|
|
if len(authHeaderParts) != 2 || authHeaderParts[0] != "Bearer" {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Invalid Authorization header format"})
|
|
}
|
|
|
|
apiKey := authHeaderParts[1]
|
|
for _, key := range appConfig.ApiKeys {
|
|
if apiKey == key {
|
|
return c.Next()
|
|
}
|
|
}
|
|
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Invalid API key"})
|
|
}
|
|
|
|
if appConfig.CORS {
|
|
var c func(ctx *fiber.Ctx) error
|
|
if appConfig.CORSAllowOrigins == "" {
|
|
c = cors.New()
|
|
} else {
|
|
c = cors.New(cors.Config{AllowOrigins: appConfig.CORSAllowOrigins})
|
|
}
|
|
|
|
app.Use(c)
|
|
}
|
|
|
|
// Load config jsons
|
|
utils.LoadConfig(appConfig.UploadDir, openai.UploadedFilesFile, &openai.UploadedFiles)
|
|
utils.LoadConfig(appConfig.ConfigsDir, openai.AssistantsConfigFile, &openai.Assistants)
|
|
utils.LoadConfig(appConfig.ConfigsDir, openai.AssistantsFileConfigFile, &openai.AssistantFiles)
|
|
|
|
galleryService := services.NewGalleryService(appConfig.ModelPath)
|
|
galleryService.Start(appConfig.Context, cl)
|
|
|
|
routes.RegisterElevenLabsRoutes(app, cl, ml, appConfig, auth)
|
|
routes.RegisterLocalAIRoutes(app, cl, ml, appConfig, galleryService, auth)
|
|
routes.RegisterOpenAIRoutes(app, cl, ml, appConfig, auth)
|
|
routes.RegisterPagesRoutes(app, cl, ml, appConfig, auth)
|
|
routes.RegisterUIRoutes(app, cl, ml, appConfig, galleryService, auth)
|
|
routes.RegisterJINARoutes(app, cl, ml, appConfig, auth)
|
|
|
|
// Define a custom 404 handler
|
|
// Note: keep this at the bottom!
|
|
app.Use(notFoundHandler)
|
|
|
|
return app, nil
|
|
}
|