routes.go 21 KB
Newer Older
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1
2
3
package server

import (
4
	"context"
Michael Yang's avatar
Michael Yang committed
5
	"crypto/sha256"
Michael Yang's avatar
Michael Yang committed
6
	"encoding/json"
7
	"errors"
8
	"fmt"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
9
	"io"
10
	"io/fs"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
11
12
13
	"log"
	"net"
	"net/http"
14
	"os"
15
	"os/signal"
Michael Yang's avatar
Michael Yang committed
16
	"path/filepath"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
17
	"reflect"
18
	"runtime"
Patrick Devine's avatar
Patrick Devine committed
19
	"strconv"
Michael Yang's avatar
Michael Yang committed
20
	"strings"
Michael Yang's avatar
Michael Yang committed
21
	"sync"
22
	"syscall"
23
	"time"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
24

Michael Yang's avatar
Michael Yang committed
25
	"github.com/gin-contrib/cors"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
26
27
	"github.com/gin-gonic/gin"

Jeffrey Morgan's avatar
Jeffrey Morgan committed
28
	"github.com/jmorganca/ollama/api"
29
	"github.com/jmorganca/ollama/llm"
Michael Yang's avatar
Michael Yang committed
30
	"github.com/jmorganca/ollama/parser"
Michael Yang's avatar
Michael Yang committed
31
	"github.com/jmorganca/ollama/version"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
32
33
)

Michael Yang's avatar
Michael Yang committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
var mode string = gin.DebugMode

func init() {
	switch mode {
	case gin.DebugMode:
	case gin.ReleaseMode:
	case gin.TestMode:
	default:
		mode = gin.DebugMode
	}

	gin.SetMode(mode)
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
48
var loaded struct {
Michael Yang's avatar
Michael Yang committed
49
50
	mu sync.Mutex

51
	runner llm.LLM
Michael Yang's avatar
Michael Yang committed
52
53
54

	expireAt    time.Time
	expireTimer *time.Timer
Jeffrey Morgan's avatar
Jeffrey Morgan committed
55

56
57
	*Model
	*api.Options
Michael Yang's avatar
Michael Yang committed
58
59
}

60
61
var defaultSessionDuration = 5 * time.Minute

Bruce MacDonald's avatar
Bruce MacDonald committed
62
// load a model into memory if it is not already loaded, it is up to the caller to lock loaded.mu before calling this function
63
func load(ctx context.Context, workDir string, model *Model, reqOpts map[string]interface{}, sessionDuration time.Duration) error {
64
65
66
	opts := api.DefaultOptions()
	if err := opts.FromMap(model.Options); err != nil {
		log.Printf("could not load model options: %v", err)
Bruce MacDonald's avatar
Bruce MacDonald committed
67
		return err
68
69
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
70
71
	if err := opts.FromMap(reqOpts); err != nil {
		return err
72
73
	}

74
	// check if the loaded model is still running in a subprocess, in case something unexpected happened
75
76
	if loaded.runner != nil {
		if err := loaded.runner.Ping(ctx); err != nil {
77
78
			log.Print("loaded llm process not responding, closing now")
			// the subprocess is no longer running, so close it
79
80
81
82
			loaded.runner.Close()
			loaded.runner = nil
			loaded.Model = nil
			loaded.Options = nil
83
84
85
		}
	}

86
87
88
89
90
91
92
	needLoad := loaded.runner == nil || // is there a model loaded?
		loaded.ModelPath != model.ModelPath || // has the base model changed?
		!reflect.DeepEqual(loaded.AdapterPaths, model.AdapterPaths) || // have the adapters changed?
		!reflect.DeepEqual(loaded.Options.Runner, opts.Runner) // have the runner options changed?

	if needLoad {
		if loaded.runner != nil {
93
			log.Println("changing loaded model")
94
95
96
97
			loaded.runner.Close()
			loaded.runner = nil
			loaded.Model = nil
			loaded.Options = nil
Michael Yang's avatar
Michael Yang committed
98
		}
Michael Yang's avatar
Michael Yang committed
99

100
		llmRunner, err := llm.New(workDir, model.ModelPath, model.AdapterPaths, opts)
Michael Yang's avatar
Michael Yang committed
101
		if err != nil {
102
103
104
105
106
107
108
			// some older models are not compatible with newer versions of llama.cpp
			// show a generalized compatibility error until there is a better way to
			// check for model compatibility
			if strings.Contains(err.Error(), "failed to load model") {
				err = fmt.Errorf("%v: this model may be incompatible with your version of Ollama. If you previously pulled this model, try updating it by running `ollama pull %s`", err, model.ShortName)
			}

Bruce MacDonald's avatar
Bruce MacDonald committed
109
			return err
Michael Yang's avatar
Michael Yang committed
110
111
		}

112
113
114
		loaded.Model = model
		loaded.runner = llmRunner
		loaded.Options = &opts
Michael Yang's avatar
Michael Yang committed
115
	}
116

Michael Yang's avatar
Michael Yang committed
117
118
119
120
	// update options for the loaded llm
	// TODO(mxyng): this isn't thread safe, but it should be fine for now
	loaded.runner.SetOptions(opts)

Jeffrey Morgan's avatar
Jeffrey Morgan committed
121
	loaded.expireAt = time.Now().Add(sessionDuration)
Bruce MacDonald's avatar
Bruce MacDonald committed
122

Jeffrey Morgan's avatar
Jeffrey Morgan committed
123
124
125
126
	if loaded.expireTimer == nil {
		loaded.expireTimer = time.AfterFunc(sessionDuration, func() {
			loaded.mu.Lock()
			defer loaded.mu.Unlock()
Michael Yang's avatar
Michael Yang committed
127

Jeffrey Morgan's avatar
Jeffrey Morgan committed
128
			if time.Now().Before(loaded.expireAt) {
Michael Yang's avatar
Michael Yang committed
129
130
131
				return
			}

132
133
			if loaded.runner != nil {
				loaded.runner.Close()
Michael Yang's avatar
Michael Yang committed
134
135
			}

136
137
138
			loaded.runner = nil
			loaded.Model = nil
			loaded.Options = nil
Michael Yang's avatar
Michael Yang committed
139
		})
Michael Yang's avatar
Michael Yang committed
140
	}
141

Jeffrey Morgan's avatar
Jeffrey Morgan committed
142
	loaded.expireTimer.Reset(sessionDuration)
Bruce MacDonald's avatar
Bruce MacDonald committed
143
144
145
146
147
148
149
150
151
152
	return nil
}

func GenerateHandler(c *gin.Context) {
	loaded.mu.Lock()
	defer loaded.mu.Unlock()

	checkpointStart := time.Now()

	var req api.GenerateRequest
Michael Yang's avatar
Michael Yang committed
153
154
155
156
157
158
159
	err := c.ShouldBindJSON(&req)
	switch {
	case errors.Is(err, io.EOF):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	case err != nil:
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
160
161
162
		return
	}

163
164
165
	// validate the request
	switch {
	case req.Model == "":
166
167
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
168
169
170
	case len(req.Format) > 0 && req.Format != "json":
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
		return
171
172
173
	case req.Raw && (req.Template != "" || req.System != "" || len(req.Context) > 0):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "raw mode does not support template, system, or context"})
		return
174
175
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
176
177
	model, err := GetModel(req.Model)
	if err != nil {
178
179
180
181
182
		var pErr *fs.PathError
		if errors.As(err, &pErr) {
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
			return
		}
Bruce MacDonald's avatar
Bruce MacDonald committed
183
184
185
186
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

187
188
189
190
191
	workDir := c.GetString("workDir")

	// TODO: set this duration from the request if specified
	sessionDuration := defaultSessionDuration
	if err := load(c.Request.Context(), workDir, model, req.Options, sessionDuration); err != nil {
192
193
194
195
		if errors.Is(err, api.ErrInvalidOpts) {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
Bruce MacDonald's avatar
Bruce MacDonald committed
196
197
198
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
199

Michael Yang's avatar
Michael Yang committed
200
201
	checkpointLoaded := time.Now()

202
203
204
205
206
207
208
	prompt := req.Prompt
	if !req.Raw {
		prompt, err = model.Prompt(req)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
Michael Yang's avatar
Michael Yang committed
209
	}
Jeffrey Morgan's avatar
Jeffrey Morgan committed
210

Michael Yang's avatar
Michael Yang committed
211
212
213
	ch := make(chan any)
	go func() {
		defer close(ch)
Michael Yang's avatar
Michael Yang committed
214
215
216
217
218
219
		// an empty request loads the model
		if req.Prompt == "" && req.Template == "" && req.System == "" {
			ch <- api.GenerateResponse{CreatedAt: time.Now().UTC(), Model: req.Model, Done: true}
			return
		}

Michael Yang's avatar
Michael Yang committed
220
		fn := func(r api.GenerateResponse) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
221
222
			loaded.expireAt = time.Now().Add(sessionDuration)
			loaded.expireTimer.Reset(sessionDuration)
Michael Yang's avatar
Michael Yang committed
223

Michael Yang's avatar
Michael Yang committed
224
225
226
			r.Model = req.Model
			r.CreatedAt = time.Now().UTC()
			if r.Done {
Michael Yang's avatar
Michael Yang committed
227
228
				r.TotalDuration = time.Since(checkpointStart)
				r.LoadDuration = checkpointLoaded.Sub(checkpointStart)
Michael Yang's avatar
Michael Yang committed
229
230
			}

231
232
233
234
235
			if req.Raw {
				// in raw mode the client must manage history on their own
				r.Context = nil
			}

Michael Yang's avatar
Michael Yang committed
236
			ch <- r
Michael Yang's avatar
Michael Yang committed
237
238
		}

239
		if err := loaded.runner.Predict(c.Request.Context(), req.Context, prompt, req.Format, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
240
			ch <- gin.H{"error": err.Error()}
Michael Yang's avatar
Michael Yang committed
241
		}
Michael Yang's avatar
Michael Yang committed
242
	}()
Michael Yang's avatar
Michael Yang committed
243

244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
	if req.Stream != nil && !*req.Stream {
		var response api.GenerateResponse
		generated := ""
		for resp := range ch {
			if r, ok := resp.(api.GenerateResponse); ok {
				generated += r.Response
				response = r
			} else {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}
		response.Response = generated
		c.JSON(http.StatusOK, response)
		return
	}

Michael Yang's avatar
Michael Yang committed
261
	streamResponse(c, ch)
Michael Yang's avatar
Michael Yang committed
262
}
Michael Yang's avatar
Michael Yang committed
263

Bruce MacDonald's avatar
Bruce MacDonald committed
264
265
266
267
268
func EmbeddingHandler(c *gin.Context) {
	loaded.mu.Lock()
	defer loaded.mu.Unlock()

	var req api.EmbeddingRequest
Michael Yang's avatar
Michael Yang committed
269
270
271
272
273
274
275
	err := c.ShouldBindJSON(&req)
	switch {
	case errors.Is(err, io.EOF):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	case err != nil:
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
276
277
278
		return
	}

279
280
281
282
283
	if req.Model == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
284
285
286
287
288
	model, err := GetModel(req.Model)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
289
290
291

	workDir := c.GetString("workDir")
	if err := load(c.Request.Context(), workDir, model, req.Options, 5*time.Minute); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
292
293
294
295
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

296
	if !loaded.Options.EmbeddingOnly {
Bruce MacDonald's avatar
Bruce MacDonald committed
297
298
299
300
		c.JSON(http.StatusBadRequest, gin.H{"error": "embedding option must be set to true"})
		return
	}

301
	embedding, err := loaded.runner.Embedding(c.Request.Context(), req.Prompt)
Bruce MacDonald's avatar
Bruce MacDonald committed
302
303
304
305
306
307
308
309
310
311
312
313
	if err != nil {
		log.Printf("embedding generation failed: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
		return
	}

	resp := api.EmbeddingResponse{
		Embedding: embedding,
	}
	c.JSON(http.StatusOK, resp)
}

314
func PullModelHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
315
	var req api.PullRequest
Michael Yang's avatar
Michael Yang committed
316
317
318
319
320
321
322
	err := c.ShouldBindJSON(&req)
	switch {
	case errors.Is(err, io.EOF):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	case err != nil:
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
323
324
325
		return
	}

326
327
328
329
330
	if req.Name == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
		return
	}

331
332
333
	ch := make(chan any)
	go func() {
		defer close(ch)
334
335
		fn := func(r api.ProgressResponse) {
			ch <- r
336
		}
337

338
339
340
341
		regOpts := &RegistryOptions{
			Insecure: req.Insecure,
		}

342
343
344
345
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

		if err := PullModel(ctx, req.Name, regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
346
			ch <- gin.H{"error": err.Error()}
347
348
349
		}
	}()

350
351
352
353
354
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

355
356
357
	streamResponse(c, ch)
}

358
func PushModelHandler(c *gin.Context) {
359
	var req api.PushRequest
Michael Yang's avatar
Michael Yang committed
360
361
362
363
364
365
366
	err := c.ShouldBindJSON(&req)
	switch {
	case errors.Is(err, io.EOF):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	case err != nil:
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
367
368
		return
	}
Michael Yang's avatar
Michael Yang committed
369

370
371
372
373
374
	if req.Name == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
		return
	}

375
376
377
	ch := make(chan any)
	go func() {
		defer close(ch)
378
379
		fn := func(r api.ProgressResponse) {
			ch <- r
380
		}
381

382
383
384
385
		regOpts := &RegistryOptions{
			Insecure: req.Insecure,
		}

Michael Yang's avatar
Michael Yang committed
386
387
388
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

389
		if err := PushModel(ctx, req.Name, regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
390
			ch <- gin.H{"error": err.Error()}
391
392
393
		}
	}()

394
395
396
397
398
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

399
400
401
	streamResponse(c, ch)
}

402
func CreateModelHandler(c *gin.Context) {
403
	var req api.CreateRequest
Michael Yang's avatar
Michael Yang committed
404
405
406
407
408
409
410
	err := c.ShouldBindJSON(&req)
	switch {
	case errors.Is(err, io.EOF):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	case err != nil:
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
411
		return
412
413
	}

Michael Yang's avatar
Michael Yang committed
414
415
	if req.Name == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
416
417
418
		return
	}

419
420
421
422
423
	if strings.Count(req.Name, ":") > 1 {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "':' (colon) is not allowed in tag names"})
		return
	}

Michael Yang's avatar
Michael Yang committed
424
425
	if req.Path == "" && req.Modelfile == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
Michael Yang's avatar
Michael Yang committed
426
427
		return
	}
Michael Yang's avatar
Michael Yang committed
428
429
430

	var modelfile io.Reader = strings.NewReader(req.Modelfile)
	if req.Path != "" && req.Modelfile == "" {
431
		mf, err := os.Open(req.Path)
Michael Yang's avatar
Michael Yang committed
432
433
434
435
		if err != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
			return
		}
436
		defer mf.Close()
Michael Yang's avatar
Michael Yang committed
437

438
		modelfile = mf
Michael Yang's avatar
Michael Yang committed
439
	}
Michael Yang's avatar
Michael Yang committed
440
441
442
443
444
445
446

	commands, err := parser.Parse(modelfile)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
447
	ch := make(chan any)
Michael Yang's avatar
Michael Yang committed
448
449
	go func() {
		defer close(ch)
450
451
		fn := func(resp api.ProgressResponse) {
			ch <- resp
452
453
		}

454
455
456
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

457
		if err := CreateModel(ctx, req.Name, filepath.Dir(req.Path), commands, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
458
			ch <- gin.H{"error": err.Error()}
459
		}
Michael Yang's avatar
Michael Yang committed
460
	}()
Michael Yang's avatar
Michael Yang committed
461

462
463
464
465
466
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

Michael Yang's avatar
Michael Yang committed
467
	streamResponse(c, ch)
Bruce MacDonald's avatar
Bruce MacDonald committed
468
469
}

470
471
func DeleteModelHandler(c *gin.Context) {
	var req api.DeleteRequest
Michael Yang's avatar
Michael Yang committed
472
473
474
475
476
477
478
	err := c.ShouldBindJSON(&req)
	switch {
	case errors.Is(err, io.EOF):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	case err != nil:
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
479
480
481
		return
	}

482
483
484
485
486
	if req.Name == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
		return
	}

487
488
489
490
	if err := DeleteModel(req.Name); err != nil {
		if os.IsNotExist(err) {
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
		} else {
491
492
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
493
494
		return
	}
Michael Yang's avatar
Michael Yang committed
495
496
497
498
499
500
501
502
503
504
505
506

	manifestsPath, err := GetManifestPath()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if err := PruneDirectory(manifestsPath); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

507
	c.JSON(http.StatusOK, nil)
508
509
}

Patrick Devine's avatar
Patrick Devine committed
510
511
func ShowModelHandler(c *gin.Context) {
	var req api.ShowRequest
Michael Yang's avatar
Michael Yang committed
512
513
514
515
516
517
518
	err := c.ShouldBindJSON(&req)
	switch {
	case errors.Is(err, io.EOF):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	case err != nil:
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Patrick Devine's avatar
Patrick Devine committed
519
520
521
		return
	}

522
523
524
525
526
	if req.Name == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
		return
	}

Patrick Devine's avatar
Patrick Devine committed
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
	resp, err := GetModelInfo(req.Name)
	if err != nil {
		if os.IsNotExist(err) {
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

	c.JSON(http.StatusOK, resp)
}

func GetModelInfo(name string) (*api.ShowResponse, error) {
	model, err := GetModel(name)
	if err != nil {
		return nil, err
	}

	resp := &api.ShowResponse{
		License:  strings.Join(model.License, "\n"),
		System:   model.System,
		Template: model.Template,
	}

	mf, err := ShowModelfile(model)
	if err != nil {
		return nil, err
	}

	resp.Modelfile = mf

	var params []string
	cs := 30
	for k, v := range model.Options {
		switch val := v.(type) {
		case string:
			params = append(params, fmt.Sprintf("%-*s %s", cs, k, val))
		case int:
			params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(val)))
		case float64:
			params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(val, 'f', 0, 64)))
		case bool:
			params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(val)))
		case []interface{}:
			for _, nv := range val {
				switch nval := nv.(type) {
				case string:
					params = append(params, fmt.Sprintf("%-*s %s", cs, k, nval))
				case int:
					params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(nval)))
				case float64:
					params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(nval, 'f', 0, 64)))
				case bool:
					params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(nval)))
				}
			}
		}
	}
	resp.Parameters = strings.Join(params, "\n")

	return resp, nil
}

591
func ListModelsHandler(c *gin.Context) {
592
	models := make([]api.ModelResponse, 0)
Patrick Devine's avatar
Patrick Devine committed
593
594
595
596
597
	fp, err := GetManifestPath()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
598
599

	walkFunc := func(path string, info os.FileInfo, _ error) error {
Patrick Devine's avatar
Patrick Devine committed
600
		if !info.IsDir() {
Michael Yang's avatar
Michael Yang committed
601
602
603
			dir, file := filepath.Split(path)
			dir = strings.Trim(strings.TrimPrefix(dir, fp), string(os.PathSeparator))
			tag := strings.Join([]string{dir, file}, ":")
604

605
			mp := ParseModelPath(tag)
Patrick Devine's avatar
Patrick Devine committed
606
			manifest, digest, err := GetManifest(mp)
Patrick Devine's avatar
Patrick Devine committed
607
			if err != nil {
608
609
				log.Printf("skipping file: %s", fp)
				return nil
Patrick Devine's avatar
Patrick Devine committed
610
			}
Michael Yang's avatar
Michael Yang committed
611
612

			models = append(models, api.ModelResponse{
Patrick Devine's avatar
Patrick Devine committed
613
614
				Name:       mp.GetShortTagname(),
				Size:       manifest.GetTotalSize(),
Patrick Devine's avatar
Patrick Devine committed
615
				Digest:     digest,
Michael Yang's avatar
Michael Yang committed
616
617
				ModifiedAt: info.ModTime(),
			})
Patrick Devine's avatar
Patrick Devine committed
618
		}
Michael Yang's avatar
Michael Yang committed
619

Patrick Devine's avatar
Patrick Devine committed
620
		return nil
Michael Yang's avatar
Michael Yang committed
621
622
623
	}

	if err := filepath.Walk(fp, walkFunc); err != nil {
Patrick Devine's avatar
Patrick Devine committed
624
625
626
627
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
628
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
629
630
}

Patrick Devine's avatar
Patrick Devine committed
631
632
func CopyModelHandler(c *gin.Context) {
	var req api.CopyRequest
Michael Yang's avatar
Michael Yang committed
633
634
635
636
637
638
639
	err := c.ShouldBindJSON(&req)
	switch {
	case errors.Is(err, io.EOF):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	case err != nil:
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Patrick Devine's avatar
Patrick Devine committed
640
641
642
		return
	}

643
644
645
646
647
	if req.Source == "" || req.Destination == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
		return
	}

Patrick Devine's avatar
Patrick Devine committed
648
649
650
651
652
653
654
655
656
657
	if err := CopyModel(req.Source, req.Destination); err != nil {
		if os.IsNotExist(err) {
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}
}

Michael Yang's avatar
Michael Yang committed
658
func HeadBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
659
660
661
662
663
664
665
666
667
668
669
	path, err := GetBlobsPath(c.Param("digest"))
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if _, err := os.Stat(path); err != nil {
		c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("blob %q not found", c.Param("digest"))})
		return
	}

Michael Yang's avatar
Michael Yang committed
670
	c.Status(http.StatusOK)
Michael Yang's avatar
Michael Yang committed
671
672
673
}

func CreateBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
674
675
676
677
678
679
	targetPath, err := GetBlobsPath(c.Param("digest"))
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
680
	hash := sha256.New()
681
	temp, err := os.CreateTemp(filepath.Dir(targetPath), c.Param("digest")+"-")
Michael Yang's avatar
Michael Yang committed
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	defer temp.Close()
	defer os.Remove(temp.Name())

	if _, err := io.Copy(temp, io.TeeReader(c.Request.Body, hash)); err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if fmt.Sprintf("sha256:%x", hash.Sum(nil)) != c.Param("digest") {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "digest does not match body"})
		return
	}

	if err := temp.Close(); err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if err := os.Rename(temp.Name(), targetPath); err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
709
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
710
711
}

Michael Yang's avatar
Michael Yang committed
712
713
714
715
716
717
718
var defaultAllowOrigins = []string{
	"localhost",
	"127.0.0.1",
	"0.0.0.0",
}

func Serve(ln net.Listener, allowOrigins []string) error {
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
	if noprune := os.Getenv("OLLAMA_NOPRUNE"); noprune == "" {
		// clean up unused layers and manifests
		if err := PruneLayers(); err != nil {
			return err
		}

		manifestsPath, err := GetManifestPath()
		if err != nil {
			return err
		}

		if err := PruneDirectory(manifestsPath); err != nil {
			return err
		}
	}

Michael Yang's avatar
Michael Yang committed
735
736
	config := cors.DefaultConfig()
	config.AllowWildcard = true
Michael Yang's avatar
Michael Yang committed
737
738
739
740
741
742
743
744
745
746

	config.AllowOrigins = allowOrigins
	for _, allowOrigin := range defaultAllowOrigins {
		config.AllowOrigins = append(config.AllowOrigins,
			fmt.Sprintf("http://%s", allowOrigin),
			fmt.Sprintf("https://%s", allowOrigin),
			fmt.Sprintf("http://%s:*", allowOrigin),
			fmt.Sprintf("https://%s:*", allowOrigin),
		)
	}
Michael Yang's avatar
Michael Yang committed
747

748
749
750
751
752
753
	workDir, err := os.MkdirTemp("", "ollama")
	if err != nil {
		return err
	}
	defer os.RemoveAll(workDir)

Bruce MacDonald's avatar
Bruce MacDonald committed
754
	r := gin.Default()
755
756
757
758
759
760
761
	r.Use(
		cors.New(config),
		func(c *gin.Context) {
			c.Set("workDir", workDir)
			c.Next()
		},
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
762

763
764
	r.POST("/api/pull", PullModelHandler)
	r.POST("/api/generate", GenerateHandler)
Bruce MacDonald's avatar
Bruce MacDonald committed
765
	r.POST("/api/embeddings", EmbeddingHandler)
766
767
	r.POST("/api/create", CreateModelHandler)
	r.POST("/api/push", PushModelHandler)
Patrick Devine's avatar
Patrick Devine committed
768
	r.POST("/api/copy", CopyModelHandler)
769
	r.DELETE("/api/delete", DeleteModelHandler)
Patrick Devine's avatar
Patrick Devine committed
770
	r.POST("/api/show", ShowModelHandler)
Michael Yang's avatar
Michael Yang committed
771
	r.POST("/api/blobs/:digest", CreateBlobHandler)
Michael Yang's avatar
Michael Yang committed
772
	r.HEAD("/api/blobs/:digest", HeadBlobHandler)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
773

Michael Yang's avatar
Michael Yang committed
774
775
776
777
778
779
780
781
	for _, method := range []string{http.MethodGet, http.MethodHead} {
		r.Handle(method, "/", func(c *gin.Context) {
			c.String(http.StatusOK, "Ollama is running")
		})

		r.Handle(method, "/api/tags", ListModelsHandler)
	}

Michael Yang's avatar
Michael Yang committed
782
	log.Printf("Listening on %s (version %s)", ln.Addr(), version.Version)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
783
784
785
786
	s := &http.Server{
		Handler: r,
	}

787
788
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
789
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
790
791
	go func() {
		<-signals
792
793
		if loaded.runner != nil {
			loaded.runner.Close()
794
		}
795
		os.RemoveAll(workDir)
796
797
798
		os.Exit(0)
	}()

799
800
801
	if runtime.GOOS == "linux" {
		// check compatibility to log warnings
		if _, err := llm.CheckVRAM(); err != nil {
802
			log.Printf(err.Error())
803
804
805
		}
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
806
807
	return s.Serve(ln)
}
Michael Yang's avatar
Michael Yang committed
808

809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
func waitForStream(c *gin.Context, ch chan interface{}) {
	c.Header("Content-Type", "application/json")
	for resp := range ch {
		switch r := resp.(type) {
		case api.ProgressResponse:
			if r.Status == "success" {
				c.JSON(http.StatusOK, r)
				return
			}
		case gin.H:
			if errorMsg, ok := r["error"].(string); ok {
				c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
				return
			} else {
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
				return
			}
		default:
			c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
			return
		}
	}
	c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
}

Michael Yang's avatar
Michael Yang committed
834
func streamResponse(c *gin.Context, ch chan any) {
835
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
836
837
838
839
840
841
842
843
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

		bts, err := json.Marshal(val)
		if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
844
			log.Printf("streamResponse: json.Marshal failed with %s", err)
Michael Yang's avatar
Michael Yang committed
845
846
847
			return false
		}

848
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
849
850
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
851
			log.Printf("streamResponse: w.Write failed with %s", err)
Michael Yang's avatar
Michael Yang committed
852
853
854
855
856
857
			return false
		}

		return true
	})
}