2024-01-05 17:04:46 +00:00
|
|
|
package backend
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-10-17 15:33:50 +00:00
|
|
|
"encoding/json"
|
2024-04-11 17:20:22 +00:00
|
|
|
"fmt"
|
2024-01-05 17:04:46 +00:00
|
|
|
"os"
|
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
"unicode/utf8"
|
|
|
|
|
2024-09-13 11:27:36 +00:00
|
|
|
"github.com/rs/zerolog/log"
|
|
|
|
|
2024-06-23 08:24:36 +00:00
|
|
|
"github.com/mudler/LocalAI/core/config"
|
|
|
|
"github.com/mudler/LocalAI/core/schema"
|
|
|
|
|
2024-06-24 15:32:12 +00:00
|
|
|
"github.com/mudler/LocalAI/core/gallery"
|
2024-06-23 08:24:36 +00:00
|
|
|
"github.com/mudler/LocalAI/pkg/grpc/proto"
|
|
|
|
model "github.com/mudler/LocalAI/pkg/model"
|
|
|
|
"github.com/mudler/LocalAI/pkg/utils"
|
2024-01-05 17:04:46 +00:00
|
|
|
)
|
|
|
|
|
2024-04-13 07:45:34 +00:00
|
|
|
type LLMResponse struct {
|
|
|
|
Response string // should this be []byte?
|
|
|
|
Usage TokenUsage
|
|
|
|
}
|
|
|
|
|
2024-04-17 21:33:49 +00:00
|
|
|
type TokenUsage struct {
|
|
|
|
Prompt int
|
|
|
|
Completion int
|
2024-04-13 07:45:34 +00:00
|
|
|
}
|
|
|
|
|
2024-09-19 10:26:53 +00:00
|
|
|
func ModelInference(ctx context.Context, s string, messages []schema.Message, images, videos, audios []string, loader *model.ModelLoader, c config.BackendConfig, o *config.ApplicationConfig, tokenCallback func(string, TokenUsage) bool) (func() (LLMResponse, error), error) {
|
2024-04-17 21:33:49 +00:00
|
|
|
modelFile := c.Model
|
2024-01-05 17:04:46 +00:00
|
|
|
|
2024-04-17 21:33:49 +00:00
|
|
|
// Check if the modelFile exists, if it doesn't try to load it from the gallery
|
|
|
|
if o.AutoloadGalleries { // experimental
|
|
|
|
if _, err := os.Stat(modelFile); os.IsNotExist(err) {
|
2024-01-05 17:04:46 +00:00
|
|
|
utils.ResetDownloadTimers()
|
|
|
|
// if we failed to load the model, we try to download it
|
2024-07-10 11:18:32 +00:00
|
|
|
err := gallery.InstallModelFromGallery(o.Galleries, modelFile, loader.ModelPath, gallery.GalleryModel{}, utils.DisplayDownloadFunction, o.EnforcePredownloadScans)
|
2024-01-05 17:04:46 +00:00
|
|
|
if err != nil {
|
2024-04-17 21:33:49 +00:00
|
|
|
return nil, err
|
2024-01-05 17:04:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-08 20:54:25 +00:00
|
|
|
opts := ModelOptions(c, o)
|
|
|
|
inferenceModel, err := loader.Load(opts...)
|
2024-01-05 17:04:46 +00:00
|
|
|
if err != nil {
|
2024-04-17 21:33:49 +00:00
|
|
|
return nil, err
|
2024-01-05 17:04:46 +00:00
|
|
|
}
|
|
|
|
|
2024-04-17 21:33:49 +00:00
|
|
|
var protoMessages []*proto.Message
|
|
|
|
// if we are using the tokenizer template, we need to convert the messages to proto messages
|
|
|
|
// unless the prompt has already been tokenized (non-chat endpoints + functions)
|
|
|
|
if c.TemplateConfig.UseTokenizerTemplate && s == "" {
|
|
|
|
protoMessages = make([]*proto.Message, len(messages), len(messages))
|
|
|
|
for i, message := range messages {
|
2024-04-11 17:20:22 +00:00
|
|
|
protoMessages[i] = &proto.Message{
|
|
|
|
Role: message.Role,
|
|
|
|
}
|
|
|
|
switch ct := message.Content.(type) {
|
|
|
|
case string:
|
|
|
|
protoMessages[i].Content = ct
|
2024-10-17 15:33:50 +00:00
|
|
|
case []interface{}:
|
|
|
|
// If using the tokenizer template, in case of multimodal we want to keep the multimodal content as and return only strings here
|
|
|
|
data, _ := json.Marshal(ct)
|
|
|
|
resultData := []struct {
|
|
|
|
Text string `json:"text"`
|
|
|
|
}{}
|
|
|
|
json.Unmarshal(data, &resultData)
|
|
|
|
for _, r := range resultData {
|
|
|
|
protoMessages[i].Content += r.Text
|
|
|
|
}
|
2024-04-11 17:20:22 +00:00
|
|
|
default:
|
2024-08-24 00:20:28 +00:00
|
|
|
return nil, fmt.Errorf("unsupported type for schema.Message.Content for inference: %T", ct)
|
2024-04-11 17:20:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-17 21:33:49 +00:00
|
|
|
// in GRPC, the backend is supposed to answer to 1 single token if stream is not supported
|
|
|
|
fn := func() (LLMResponse, error) {
|
|
|
|
opts := gRPCPredictOpts(c, loader.ModelPath)
|
|
|
|
opts.Prompt = s
|
|
|
|
opts.Messages = protoMessages
|
|
|
|
opts.UseTokenizerTemplate = c.TemplateConfig.UseTokenizerTemplate
|
|
|
|
opts.Images = images
|
2024-09-19 09:21:59 +00:00
|
|
|
opts.Videos = videos
|
2024-09-19 10:26:53 +00:00
|
|
|
opts.Audios = audios
|
2024-01-05 17:04:46 +00:00
|
|
|
|
2024-04-17 21:33:49 +00:00
|
|
|
tokenUsage := TokenUsage{}
|
2024-01-05 17:04:46 +00:00
|
|
|
|
2024-04-17 21:33:49 +00:00
|
|
|
// check the per-model feature flag for usage, since tokenCallback may have a cost.
|
|
|
|
// Defaults to off as for now it is still experimental
|
|
|
|
if c.FeatureFlag.Enabled("usage") {
|
|
|
|
userTokenCallback := tokenCallback
|
|
|
|
if userTokenCallback == nil {
|
|
|
|
userTokenCallback = func(token string, usage TokenUsage) bool {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
2024-01-05 17:04:46 +00:00
|
|
|
|
2024-04-17 21:33:49 +00:00
|
|
|
promptInfo, pErr := inferenceModel.TokenizeString(ctx, opts)
|
|
|
|
if pErr == nil && promptInfo.Length > 0 {
|
|
|
|
tokenUsage.Prompt = int(promptInfo.Length)
|
|
|
|
}
|
2024-01-05 17:04:46 +00:00
|
|
|
|
2024-04-17 21:33:49 +00:00
|
|
|
tokenCallback = func(token string, usage TokenUsage) bool {
|
|
|
|
tokenUsage.Completion++
|
|
|
|
return userTokenCallback(token, tokenUsage)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if tokenCallback != nil {
|
|
|
|
ss := ""
|
2024-01-05 17:04:46 +00:00
|
|
|
|
|
|
|
var partialRune []byte
|
2024-12-08 16:53:36 +00:00
|
|
|
err := inferenceModel.PredictStream(ctx, opts, func(chars []byte) {
|
|
|
|
partialRune = append(partialRune, chars...)
|
2024-01-05 17:04:46 +00:00
|
|
|
|
|
|
|
for len(partialRune) > 0 {
|
|
|
|
r, size := utf8.DecodeRune(partialRune)
|
|
|
|
if r == utf8.RuneError {
|
|
|
|
// incomplete rune, wait for more bytes
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
2024-04-17 21:33:49 +00:00
|
|
|
tokenCallback(string(r), tokenUsage)
|
2024-01-05 17:04:46 +00:00
|
|
|
ss += string(r)
|
|
|
|
|
|
|
|
partialRune = partialRune[size:]
|
|
|
|
}
|
|
|
|
})
|
2024-04-17 21:33:49 +00:00
|
|
|
return LLMResponse{
|
|
|
|
Response: ss,
|
|
|
|
Usage: tokenUsage,
|
|
|
|
}, err
|
|
|
|
} else {
|
|
|
|
// TODO: Is the chicken bit the only way to get here? is that acceptable?
|
|
|
|
reply, err := inferenceModel.Predict(ctx, opts)
|
2024-01-05 17:04:46 +00:00
|
|
|
if err != nil {
|
2024-04-17 21:33:49 +00:00
|
|
|
return LLMResponse{}, err
|
2024-01-05 17:04:46 +00:00
|
|
|
}
|
2024-04-15 17:47:11 +00:00
|
|
|
if tokenUsage.Prompt == 0 {
|
|
|
|
tokenUsage.Prompt = int(reply.PromptTokens)
|
|
|
|
}
|
|
|
|
if tokenUsage.Completion == 0 {
|
|
|
|
tokenUsage.Completion = int(reply.Tokens)
|
|
|
|
}
|
2024-04-17 21:33:49 +00:00
|
|
|
return LLMResponse{
|
|
|
|
Response: string(reply.Message),
|
|
|
|
Usage: tokenUsage,
|
|
|
|
}, err
|
2024-04-13 07:45:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-17 21:33:49 +00:00
|
|
|
return fn, nil
|
2024-04-13 07:45:34 +00:00
|
|
|
}
|
2024-01-05 17:04:46 +00:00
|
|
|
|
2024-04-17 21:33:49 +00:00
|
|
|
var cutstrings map[string]*regexp.Regexp = make(map[string]*regexp.Regexp)
|
|
|
|
var mu sync.Mutex = sync.Mutex{}
|
|
|
|
|
|
|
|
func Finetune(config config.BackendConfig, input, prediction string) string {
|
2024-01-05 17:04:46 +00:00
|
|
|
if config.Echo {
|
|
|
|
prediction = input + prediction
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, c := range config.Cutstrings {
|
2024-04-17 21:33:49 +00:00
|
|
|
mu.Lock()
|
|
|
|
reg, ok := cutstrings[c]
|
2024-01-05 17:04:46 +00:00
|
|
|
if !ok {
|
2024-09-13 11:27:36 +00:00
|
|
|
r, err := regexp.Compile(c)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal().Err(err).Msg("failed to compile regex")
|
|
|
|
}
|
|
|
|
cutstrings[c] = r
|
2024-04-17 21:33:49 +00:00
|
|
|
reg = cutstrings[c]
|
2024-01-05 17:04:46 +00:00
|
|
|
}
|
2024-04-17 21:33:49 +00:00
|
|
|
mu.Unlock()
|
2024-01-05 17:04:46 +00:00
|
|
|
prediction = reg.ReplaceAllString(prediction, "")
|
|
|
|
}
|
|
|
|
|
2024-09-13 11:27:36 +00:00
|
|
|
// extract results from the response which can be for instance inside XML tags
|
|
|
|
var predResult string
|
|
|
|
for _, r := range config.ExtractRegex {
|
|
|
|
mu.Lock()
|
|
|
|
reg, ok := cutstrings[r]
|
|
|
|
if !ok {
|
|
|
|
regex, err := regexp.Compile(r)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal().Err(err).Msg("failed to compile regex")
|
|
|
|
}
|
|
|
|
cutstrings[r] = regex
|
|
|
|
reg = regex
|
|
|
|
}
|
|
|
|
mu.Unlock()
|
|
|
|
predResult += reg.FindString(prediction)
|
|
|
|
}
|
|
|
|
if predResult != "" {
|
|
|
|
prediction = predResult
|
|
|
|
}
|
|
|
|
|
2024-01-05 17:04:46 +00:00
|
|
|
for _, c := range config.TrimSpace {
|
|
|
|
prediction = strings.TrimSpace(strings.TrimPrefix(prediction, c))
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, c := range config.TrimSuffix {
|
|
|
|
prediction = strings.TrimSpace(strings.TrimSuffix(prediction, c))
|
|
|
|
}
|
|
|
|
return prediction
|
|
|
|
}
|