|
| 1 | +package gallery |
| 2 | + |
| 3 | +import ( |
| 4 | + "os" |
| 5 | + "path/filepath" |
| 6 | + "strings" |
| 7 | + "sync" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/mudler/LocalAI/pkg/downloader" |
| 11 | + "github.com/mudler/LocalAI/pkg/xsync" |
| 12 | + "github.com/mudler/xlog" |
| 13 | + "gopkg.in/yaml.v3" |
| 14 | +) |
| 15 | + |
| 16 | +// modelConfigCacheEntry holds a cached parsed config_file map from a URL-referenced model config. |
| 17 | +type modelConfigCacheEntry struct { |
| 18 | + configMap map[string]interface{} |
| 19 | + lastUpdated time.Time |
| 20 | +} |
| 21 | + |
| 22 | +func (e modelConfigCacheEntry) hasExpired() bool { |
| 23 | + return e.lastUpdated.Before(time.Now().Add(-1 * time.Hour)) |
| 24 | +} |
| 25 | + |
| 26 | +// modelConfigCache caches parsed model config maps keyed by URL. |
| 27 | +var modelConfigCache = xsync.NewSyncedMap[string, modelConfigCacheEntry]() |
| 28 | + |
| 29 | +// resolveBackend determines the backend for a GalleryModel by checking (in priority order): |
| 30 | +// 1. Overrides["backend"] — highest priority, same as install-time merge |
| 31 | +// 2. Inline ConfigFile["backend"] — for models with inline config maps |
| 32 | +// 3. URL-referenced config file — fetched, parsed, and cached |
| 33 | +// |
| 34 | +// The model's URL should already be resolved (local override applied) before calling this. |
| 35 | +func resolveBackend(m *GalleryModel, basePath string) string { |
| 36 | + // 1. Overrides take priority (matches install-time mergo.WithOverride behavior) |
| 37 | + if b, ok := m.Overrides["backend"].(string); ok && b != "" { |
| 38 | + return b |
| 39 | + } |
| 40 | + |
| 41 | + // 2. Inline config_file map |
| 42 | + if b, ok := m.ConfigFile["backend"].(string); ok && b != "" { |
| 43 | + return b |
| 44 | + } |
| 45 | + |
| 46 | + // 3. Fetch and parse the URL-referenced config |
| 47 | + if m.URL != "" { |
| 48 | + configMap := fetchModelConfigMap(m.URL, basePath) |
| 49 | + if b, ok := configMap["backend"].(string); ok && b != "" { |
| 50 | + return b |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return "" |
| 55 | +} |
| 56 | + |
| 57 | +// fetchModelConfigMap fetches a model config URL, parses the config_file YAML string |
| 58 | +// inside it, and returns the result as a map. Results are cached for 1 hour. |
| 59 | +// Local file:// URLs skip the cache so edits are picked up immediately. |
| 60 | +func fetchModelConfigMap(modelURL, basePath string) map[string]interface{} { |
| 61 | + // Check cache (skip for file:// URLs so local edits are picked up immediately) |
| 62 | + isLocal := strings.HasPrefix(modelURL, downloader.LocalPrefix) |
| 63 | + if !isLocal && modelConfigCache.Exists(modelURL) { |
| 64 | + entry := modelConfigCache.Get(modelURL) |
| 65 | + if !entry.hasExpired() { |
| 66 | + return entry.configMap |
| 67 | + } |
| 68 | + modelConfigCache.Delete(modelURL) |
| 69 | + } |
| 70 | + |
| 71 | + // Reuse existing gallery config fetcher |
| 72 | + modelConfig, err := GetGalleryConfigFromURL[ModelConfig](modelURL, basePath) |
| 73 | + if err != nil { |
| 74 | + xlog.Debug("Failed to fetch model config for backend resolution", "url", modelURL, "error", err) |
| 75 | + // Cache the failure for remote URLs to avoid repeated fetch attempts |
| 76 | + if !isLocal { |
| 77 | + modelConfigCache.Set(modelURL, modelConfigCacheEntry{ |
| 78 | + configMap: map[string]interface{}{}, |
| 79 | + lastUpdated: time.Now(), |
| 80 | + }) |
| 81 | + } |
| 82 | + return map[string]interface{}{} |
| 83 | + } |
| 84 | + |
| 85 | + // Parse the config_file YAML string into a map |
| 86 | + configMap := make(map[string]interface{}) |
| 87 | + if modelConfig.ConfigFile != "" { |
| 88 | + if err := yaml.Unmarshal([]byte(modelConfig.ConfigFile), &configMap); err != nil { |
| 89 | + xlog.Debug("Failed to parse config_file for backend resolution", "url", modelURL, "error", err) |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + // Cache for remote URLs |
| 94 | + if !isLocal { |
| 95 | + modelConfigCache.Set(modelURL, modelConfigCacheEntry{ |
| 96 | + configMap: configMap, |
| 97 | + lastUpdated: time.Now(), |
| 98 | + }) |
| 99 | + } |
| 100 | + |
| 101 | + return configMap |
| 102 | +} |
| 103 | + |
| 104 | +// prefetchModelConfigs fetches model config URLs in parallel to warm the cache. |
| 105 | +// This avoids sequential HTTP requests on cold start (~50 unique gallery files). |
| 106 | +func prefetchModelConfigs(urls []string, basePath string) { |
| 107 | + const maxConcurrency = 10 |
| 108 | + sem := make(chan struct{}, maxConcurrency) |
| 109 | + var wg sync.WaitGroup |
| 110 | + for _, url := range urls { |
| 111 | + wg.Add(1) |
| 112 | + go func(u string) { |
| 113 | + defer wg.Done() |
| 114 | + sem <- struct{}{} |
| 115 | + defer func() { <-sem }() |
| 116 | + fetchModelConfigMap(u, basePath) |
| 117 | + }(url) |
| 118 | + } |
| 119 | + wg.Wait() |
| 120 | +} |
| 121 | + |
| 122 | +// resolveModelURLLocally attempts to resolve a github: model URL to a local file:// |
| 123 | +// path when the gallery itself was loaded from a local path. This supports development |
| 124 | +// workflows where new model files are added locally before being pushed to GitHub. |
| 125 | +// |
| 126 | +// For example, if the gallery was loaded from file:///path/to/gallery/index.yaml |
| 127 | +// and a model references github:mudler/LocalAI/gallery/foo.yaml@master, this will |
| 128 | +// check if /path/to/gallery/foo.yaml exists locally and return file:///path/to/gallery/foo.yaml. |
| 129 | +// |
| 130 | +// This is applied to model.URL in AvailableGalleryModels so that both listing (backend |
| 131 | +// resolution) and installation use the same resolved URL. |
| 132 | +func resolveModelURLLocally(modelURL, galleryURL string) string { |
| 133 | + galleryDir := localGalleryDir(galleryURL) |
| 134 | + if galleryDir == "" { |
| 135 | + return modelURL |
| 136 | + } |
| 137 | + |
| 138 | + // Only handle github: URLs |
| 139 | + if !strings.HasPrefix(modelURL, downloader.GithubURI) && !strings.HasPrefix(modelURL, downloader.GithubURI2) { |
| 140 | + return modelURL |
| 141 | + } |
| 142 | + |
| 143 | + // Extract the filename from the github URL |
| 144 | + // Format: github:org/repo/path/to/file.yaml@branch |
| 145 | + raw := strings.TrimPrefix(modelURL, downloader.GithubURI2) |
| 146 | + raw = strings.TrimPrefix(raw, downloader.GithubURI) |
| 147 | + // Remove @branch suffix |
| 148 | + if idx := strings.LastIndex(raw, "@"); idx >= 0 { |
| 149 | + raw = raw[:idx] |
| 150 | + } |
| 151 | + filename := filepath.Base(raw) |
| 152 | + |
| 153 | + localPath := filepath.Join(galleryDir, filename) |
| 154 | + if _, err := os.Stat(localPath); err == nil { |
| 155 | + return downloader.LocalPrefix + localPath |
| 156 | + } |
| 157 | + |
| 158 | + return modelURL |
| 159 | +} |
| 160 | + |
| 161 | +// localGalleryDir returns the directory of a gallery URL if it's local, or "" if remote. |
| 162 | +func localGalleryDir(galleryURL string) string { |
| 163 | + if strings.HasPrefix(galleryURL, downloader.LocalPrefix) { |
| 164 | + return filepath.Dir(strings.TrimPrefix(galleryURL, downloader.LocalPrefix)) |
| 165 | + } |
| 166 | + // Plain path (no scheme) that exists on disk |
| 167 | + if !strings.Contains(galleryURL, "://") && !strings.HasPrefix(galleryURL, downloader.GithubURI) { |
| 168 | + if info, err := os.Stat(galleryURL); err == nil && !info.IsDir() { |
| 169 | + return filepath.Dir(galleryURL) |
| 170 | + } |
| 171 | + } |
| 172 | + return "" |
| 173 | +} |
0 commit comments