forked from sammcj/gollama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoperations.go
387 lines (347 loc) · 11 KB
/
operations.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package main
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/charmbracelet/bubbles/progress"
"github.com/charmbracelet/bubbles/table"
tea "github.com/charmbracelet/bubbletea"
"github.com/ollama/ollama/api"
"github.com/sammcj/gollama/logging"
)
func runModel(model string) tea.Cmd {
ollamaPath, err := exec.LookPath("ollama")
if err != nil {
logging.ErrorLogger.Printf("Error finding ollama binary: %v\n", err)
return nil
}
c := exec.Command(ollamaPath, "run", model)
return tea.ExecProcess(c, func(err error) tea.Msg {
if err != nil {
logging.ErrorLogger.Printf("Error running model: %v\n", err)
}
return runFinishedMessage{err}
})
}
func deleteModel(client *api.Client, name string) error {
ctx := context.Background()
req := &api.DeleteRequest{Name: name}
logging.DebugLogger.Printf("Attempting to delete model: %s\n", name)
err := client.Delete(ctx, req)
if err != nil {
logging.ErrorLogger.Printf("Error deleting model %s: %v\n", name, err)
return fmt.Errorf("error deleting model %s: %v", name, err)
}
logging.InfoLogger.Printf("Successfully deleted model: %s\n", name)
return nil
}
func (m *AppModel) startPushModel(modelName string) tea.Cmd {
logging.InfoLogger.Printf("Pushing model: %s\n", modelName)
// Initialize the progress model
m.progress = progress.New(progress.WithDefaultGradient())
return tea.Batch(
tea.Tick(time.Millisecond*100, func(t time.Time) tea.Msg {
return progressMsg{modelName: modelName}
}),
m.pushModelCmd(modelName),
)
}
func (m *AppModel) pushModelCmd(modelName string) tea.Cmd {
return func() tea.Msg {
ctx := context.Background()
req := &api.PushRequest{Name: modelName}
err := m.client.Push(ctx, req, func(resp api.ProgressResponse) error {
m.progress.SetPercent(float64(resp.Completed) / float64(resp.Total))
return nil
})
if err != nil {
return pushErrorMsg{err}
}
return pushSuccessMsg{modelName}
}
}
func linkModel(modelName, lmStudioModelsDir string, noCleanup bool) (string, error) {
modelPath, err := getModelPath(modelName)
if err != nil {
return "", fmt.Errorf("error getting model path for %s: %v", modelName, err)
}
parts := strings.Split(modelName, ":")
author := "unknown"
if len(parts) > 1 {
author = strings.ReplaceAll(parts[0], "/", "-")
}
lmStudioModelName := strings.ReplaceAll(strings.ReplaceAll(modelName, ":", "-"), "_", "-")
lmStudioModelDir := filepath.Join(lmStudioModelsDir, author, lmStudioModelName+"-GGUF")
// Check if the model path is a valid file
fileInfo, err := os.Stat(modelPath)
if err != nil || fileInfo.IsDir() {
return "", fmt.Errorf("invalid model path for %s: %s", modelName, modelPath)
}
// Check if the symlink already exists and is valid
lmStudioModelPath := filepath.Join(lmStudioModelDir, filepath.Base(lmStudioModelName)+".gguf")
if _, err := os.Lstat(lmStudioModelPath); err == nil {
if isValidSymlink(lmStudioModelPath, modelPath) {
message := "Model %s is already symlinked to %s"
logging.InfoLogger.Printf(message+"\n", modelName, lmStudioModelPath)
return "", nil
}
// Remove the invalid symlink
err = os.Remove(lmStudioModelPath)
if err != nil {
message := "failed to remove invalid symlink %s: %v"
logging.ErrorLogger.Printf(message+"\n", lmStudioModelPath, err)
return "", fmt.Errorf(message, lmStudioModelPath, err)
}
}
// Check if the model is already symlinked in another location
var existingSymlinkPath string
err = filepath.Walk(lmStudioModelsDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.Mode()&os.ModeSymlink != 0 {
linkPath, err := os.Readlink(path)
if err != nil {
return err
}
if linkPath == modelPath {
existingSymlinkPath = path
return nil
}
}
return nil
})
if err != nil {
message := "error walking LM Studio models directory: %v"
logging.ErrorLogger.Printf(message+"\n", err)
return "", fmt.Errorf(message, err)
}
if existingSymlinkPath != "" {
// Remove the duplicated model directory
err = os.RemoveAll(lmStudioModelDir)
if err != nil {
message := "failed to remove duplicated model directory %s: %v"
logging.ErrorLogger.Printf(message+"\n", lmStudioModelDir, err)
return "", fmt.Errorf(message, lmStudioModelDir, err)
}
return fmt.Sprintf("Removed duplicated model directory %s", lmStudioModelDir), nil
}
// Create the symlink
err = os.MkdirAll(lmStudioModelDir, os.ModePerm)
if err != nil {
message := "failed to create directory %s: %v"
logging.ErrorLogger.Printf(message+"\n", lmStudioModelDir, err)
return "", fmt.Errorf(message, lmStudioModelDir, err)
}
err = os.Symlink(modelPath, lmStudioModelPath)
if err != nil {
message := "failed to symlink %s: %v"
logging.ErrorLogger.Printf(message+"\n", modelName, err)
return "", fmt.Errorf(message, modelName, err)
}
if !noCleanup {
cleanBrokenSymlinks(lmStudioModelsDir)
}
message := "Symlinked %s to %s"
logging.InfoLogger.Printf(message+"\n", modelName, lmStudioModelPath)
return "", nil
}
func getModelPath(modelName string) (string, error) {
cmd := exec.Command("ollama", "show", "--modelfile", modelName)
output, err := cmd.Output()
if err != nil {
return "", err
}
lines := strings.Split(strings.TrimSpace(string(output)), "\n")
for _, line := range lines {
if strings.HasPrefix(line, "FROM ") {
return strings.TrimSpace(line[5:]), nil
}
}
message := "failed to get model path for %s: no 'FROM' line in output"
logging.ErrorLogger.Printf(message+"\n", modelName)
return "", fmt.Errorf(message, modelName)
}
func cleanBrokenSymlinks(lmStudioModelsDir string) {
err := filepath.Walk(lmStudioModelsDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
files, err := os.ReadDir(path)
if err != nil {
return err
}
if len(files) == 0 {
logging.InfoLogger.Printf("Removing empty directory: %s\n", path)
err = os.Remove(path)
if err != nil {
return err
}
}
} else if info.Mode()&os.ModeSymlink != 0 {
linkPath, err := os.Readlink(path)
if err != nil {
return err
}
if !isValidSymlink(path, linkPath) {
logging.InfoLogger.Printf("Removing invalid symlink: %s\n", path)
err = os.Remove(path)
if err != nil {
return err
}
}
}
return nil
})
if err != nil {
logging.ErrorLogger.Printf("Error walking LM Studio models directory: %v\n", err)
return
}
}
func isValidSymlink(symlinkPath, targetPath string) bool {
// Check if the symlink matches the expected naming convention
expectedSuffix := ".gguf"
if !strings.HasSuffix(filepath.Base(symlinkPath), expectedSuffix) {
return false
}
// Check if the target file exists
if _, err := os.Stat(targetPath); os.IsNotExist(err) {
return false
}
// Check if the symlink target is a file (not a directory or another symlink)
fileInfo, err := os.Lstat(targetPath)
if err != nil || fileInfo.Mode()&os.ModeSymlink != 0 || fileInfo.IsDir() {
logging.DebugLogger.Printf("Symlink target is not a file: %s\n", targetPath)
return false
}
return true
}
func cleanupSymlinkedModels(lmStudioModelsDir string) {
for {
hasEmptyDir := false
err := filepath.Walk(lmStudioModelsDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
files, err := os.ReadDir(path)
if err != nil {
return err
}
if len(files) == 0 {
logging.InfoLogger.Printf("Removing empty directory: %s\n", path)
err = os.Remove(path)
if err != nil {
return err
}
hasEmptyDir = true
}
} else if info.Mode()&os.ModeSymlink != 0 {
logging.InfoLogger.Printf("Removing symlinked model: %s\n", path)
err = os.Remove(path)
if err != nil {
return err
}
}
return nil
})
if err != nil {
logging.ErrorLogger.Printf("Error walking LM Studio models directory: %v\n", err)
return
}
if !hasEmptyDir {
break
}
}
}
func copyModel(client *api.Client, oldName string, newName string) {
ctx := context.Background()
req := &api.CopyRequest{
Source: oldName,
Destination: newName,
}
err := client.Copy(ctx, req)
if err != nil {
logging.ErrorLogger.Printf("Error copying model: %v\n", err)
return
}
logging.InfoLogger.Printf("Successfully copied model: %s to %s\n", oldName, newName)
// Push the new model to the Ollama API
err = pushModel(client, newName)
if err != nil {
logging.ErrorLogger.Printf("Error pushing model: %v\n", err)
}
}
func pushModel(client *api.Client, modelName string) error {
ctx := context.Background()
req := &api.PushRequest{Name: modelName}
err := client.Push(ctx, req, func(resp api.ProgressResponse) error {
return nil
})
if err != nil {
return fmt.Errorf("error pushing model: %w", err)
}
logging.InfoLogger.Printf("Successfully pushed model: %s\n", modelName)
return nil
}
// Adding a new function get use client to get the running models
func showRunningModels(client *api.Client) ([]table.Row, error) {
ctx := context.Background()
resp, err := client.ListRunning(ctx)
if err != nil {
return nil, fmt.Errorf("error fetching running models: %v", err)
}
var runningModels []table.Row
for _, model := range resp.Models {
name := model.Name
size := float64(model.Size) / 1024 / 1024 / 1024
vram := float64(model.SizeVRAM) / 1024 / 1024 / 1024
until := model.ExpiresAt.Format("2006-01-02 15:04:05")
runningModels = append(runningModels, table.Row{name, fmt.Sprintf("%.2f GB", size), fmt.Sprintf("%.2f GB", vram), until})
logging.DebugLogger.Printf("Running model: %s\n", name)
}
return runningModels, nil
}
func copyModelfile(modelName, newModelName string) (string, error) {
logging.InfoLogger.Printf("Copying modelfile for model: %s\n", modelName)
cmd := exec.Command("ollama", "show", "--modelfile", modelName)
output, err := cmd.Output()
if err != nil {
logging.ErrorLogger.Printf("Error copying modelfile for model %s: %v\n", modelName, err)
return "", err
}
err = os.MkdirAll(filepath.Join(os.Getenv("HOME"), ".config", "gollama", "modelfiles"), os.ModePerm)
if err != nil {
logging.ErrorLogger.Printf("Error creating modelfiles directory: %v\n", err)
return "", err
}
newModelfilePath := filepath.Join(os.Getenv("HOME"), ".config", "gollama", "modelfiles", newModelName+".modelfile")
err = os.WriteFile(newModelfilePath, output, 0644)
if err != nil {
logging.ErrorLogger.Printf("Error writing modelfile for model %s: %v\n", modelName, err)
return "", err
}
logging.InfoLogger.Printf("Copied modelfile to: %s\n", newModelfilePath)
return newModelfilePath, nil
}
type editorFinishedMsg struct{ err error }
func openEditor(filePath string) tea.Cmd {
logging.DebugLogger.Printf("Opening editor for file: %s\n", filePath)
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "vim"
}
c := exec.Command(editor, filePath)
return tea.ExecProcess(c, func(err error) tea.Msg {
return editorFinishedMsg{err}
})
}
func createModelFromModelfile(modelName, modelfilePath string) error {
cmd := exec.Command("ollama", "create", "-f", modelfilePath, modelName)
return cmd.Run()
}