(ctx context.Context, s string, tokens []int, loader *model.ModelLoader, modelConfig config.ModelConfig, appConfig *config.ApplicationConfig)
| 39 | } |
| 40 | |
| 41 | func ModelEmbedding(ctx context.Context, s string, tokens []int, loader *model.ModelLoader, modelConfig config.ModelConfig, appConfig *config.ApplicationConfig) (func() ([]float32, error), error) { |
| 42 | |
| 43 | // model.WithContext(ctx) overrides the app-context default set in |
| 44 | // ModelOptions so distributed routing decisions reach the request's |
| 45 | // X-LocalAI-Node holder via distributedhdr.Stamp. |
| 46 | opts := ModelOptions(modelConfig, appConfig, model.WithContext(ctx)) |
| 47 | |
| 48 | inferenceModel, err := loader.Load(opts...) |
| 49 | if err != nil { |
| 50 | recordModelLoadFailure(appConfig, modelConfig.Name, modelConfig.Backend, err, nil) |
| 51 | return nil, err |
| 52 | } |
| 53 | |
| 54 | var fn func() ([]float32, error) |
| 55 | switch model := inferenceModel.(type) { |
| 56 | case grpc.Backend: |
| 57 | fn = func() ([]float32, error) { |
| 58 | predictOptions := gRPCPredictOpts(modelConfig, loader.ModelPath) |
| 59 | if len(tokens) > 0 { |
| 60 | embeds := []int32{} |
| 61 | |
| 62 | for _, t := range tokens { |
| 63 | embeds = append(embeds, int32(t)) |
| 64 | } |
| 65 | predictOptions.EmbeddingTokens = embeds |
| 66 | |
| 67 | res, err := model.Embeddings(appConfig.Context, predictOptions) |
| 68 | if err != nil { |
| 69 | return nil, err |
| 70 | } |
| 71 | |
| 72 | return res.Embeddings, nil |
| 73 | } |
| 74 | predictOptions.Embeddings = s |
| 75 | |
| 76 | res, err := model.Embeddings(appConfig.Context, predictOptions) |
| 77 | if err != nil { |
| 78 | return nil, err |
| 79 | } |
| 80 | |
| 81 | return res.Embeddings, nil |
| 82 | } |
| 83 | default: |
| 84 | fn = func() ([]float32, error) { |
| 85 | return nil, fmt.Errorf("embeddings not supported by the backend") |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | wrappedFn := func() ([]float32, error) { |
| 90 | embeds, err := fn() |
| 91 | if err != nil { |
| 92 | return embeds, err |
| 93 | } |
| 94 | // Return embeddings as-is to preserve full dimensionality |
| 95 | // Trailing zeros may be valid values in some embedding models |
| 96 | return embeds, nil |
| 97 | } |
| 98 |
no test coverage detected