routes.go 26.7 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
	"encoding/json"
6
	"errors"
7
	"fmt"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
8
	"io"
9
	"io/fs"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
10
11
12
	"log"
	"net"
	"net/http"
13
	"os"
14
	"os/signal"
Michael Yang's avatar
Michael Yang committed
15
	"path/filepath"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
16
	"reflect"
17
	"runtime"
Patrick Devine's avatar
Patrick Devine committed
18
	"strconv"
Michael Yang's avatar
Michael Yang committed
19
	"strings"
Michael Yang's avatar
Michael Yang committed
20
	"sync"
21
	"syscall"
22
	"time"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
23

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
27
	"github.com/jmorganca/ollama/api"
28
	"github.com/jmorganca/ollama/gpu"
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
var mode string = gin.DebugMode

36
37
38
39
type Server struct {
	WorkDir string
}

Michael Yang's avatar
Michael Yang committed
40
41
42
43
44
45
46
47
48
49
50
51
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
52
var loaded struct {
Michael Yang's avatar
Michael Yang committed
53
54
	mu sync.Mutex

55
	runner llm.LLM
Michael Yang's avatar
Michael Yang committed
56
57
58

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

60
61
	*Model
	*api.Options
Michael Yang's avatar
Michael Yang committed
62
63
}

64
65
var defaultSessionDuration = 5 * time.Minute

Bruce MacDonald's avatar
Bruce MacDonald committed
66
// 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
Bruce MacDonald's avatar
Bruce MacDonald committed
67
68
69
70
71
72
73
74
func load(c *gin.Context, modelName string, reqOpts map[string]interface{}, sessionDuration time.Duration) (*Model, error) {
	model, err := GetModel(modelName)
	if err != nil {
		return nil, err
	}

	workDir := c.GetString("workDir")

75
76
77
	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
78
		return nil, err
79
80
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
81
	if err := opts.FromMap(reqOpts); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
82
		return nil, err
83
84
	}

85
86
87
88
89
90
91
	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 {
92
			log.Println("changing loaded model")
93
94
95
96
			loaded.runner.Close()
			loaded.runner = nil
			loaded.Model = nil
			loaded.Options = nil
Michael Yang's avatar
Michael Yang committed
97
		}
Michael Yang's avatar
Michael Yang committed
98

Michael Yang's avatar
Michael Yang committed
99
		llmRunner, err := llm.New(workDir, model.ModelPath, model.AdapterPaths, model.ProjectorPaths, opts)
Michael Yang's avatar
Michael Yang committed
100
		if err != nil {
101
102
103
			// 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
Bruce MacDonald's avatar
Bruce MacDonald committed
104
			if errors.Is(llm.ErrUnsupportedFormat, err) || strings.Contains(err.Error(), "failed to load model") {
105
106
107
				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
108
			return nil, err
Michael Yang's avatar
Michael Yang committed
109
110
		}

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

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
118
119
120
121
	if loaded.expireTimer == nil {
		loaded.expireTimer = time.AfterFunc(sessionDuration, func() {
			loaded.mu.Lock()
			defer loaded.mu.Unlock()
Michael Yang's avatar
Michael Yang committed
122

Jeffrey Morgan's avatar
Jeffrey Morgan committed
123
			if time.Now().Before(loaded.expireAt) {
Michael Yang's avatar
Michael Yang committed
124
125
126
				return
			}

127
128
			if loaded.runner != nil {
				loaded.runner.Close()
Michael Yang's avatar
Michael Yang committed
129
130
			}

131
132
133
			loaded.runner = nil
			loaded.Model = nil
			loaded.Options = nil
Michael Yang's avatar
Michael Yang committed
134
		})
Michael Yang's avatar
Michael Yang committed
135
	}
136

Jeffrey Morgan's avatar
Jeffrey Morgan committed
137
	loaded.expireTimer.Reset(sessionDuration)
Bruce MacDonald's avatar
Bruce MacDonald committed
138
	return model, nil
Bruce MacDonald's avatar
Bruce MacDonald committed
139
140
141
142
143
144
145
146
}

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
147
	err := c.ShouldBindJSON(&req)
Patrick Devine's avatar
Patrick Devine committed
148

Michael Yang's avatar
Michael Yang committed
149
150
151
152
153
154
	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
155
156
157
		return
	}

158
159
160
	// validate the request
	switch {
	case req.Model == "":
161
162
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
163
164
165
	case len(req.Format) > 0 && req.Format != "json":
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
		return
166
167
168
	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
169
170
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
171
172
	sessionDuration := defaultSessionDuration
	model, err := load(c, req.Model, req.Options, sessionDuration)
Bruce MacDonald's avatar
Bruce MacDonald committed
173
	if err != nil {
174
		var pErr *fs.PathError
Bruce MacDonald's avatar
Bruce MacDonald committed
175
176
		switch {
		case errors.As(err, &pErr):
177
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
Bruce MacDonald's avatar
Bruce MacDonald committed
178
179
180
181
		case errors.Is(err, api.ErrInvalidOpts):
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
182
		}
Bruce MacDonald's avatar
Bruce MacDonald committed
183
184
185
		return
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
186
187
	// an empty request loads the model
	if req.Prompt == "" && req.Template == "" && req.System == "" {
188
		c.JSON(http.StatusOK, api.GenerateResponse{
189
190
191
			CreatedAt: time.Now().UTC(),
			Model:     req.Model,
			Done:      true})
Bruce MacDonald's avatar
Bruce MacDonald committed
192
193
194
195
196
		return
	}

	checkpointLoaded := time.Now()

Bruce MacDonald's avatar
Bruce MacDonald committed
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
	var prompt string
	switch {
	case req.Raw:
		prompt = req.Prompt
	case req.Prompt != "":
		if req.Template != "" {
			// override the default model template
			model.Template = req.Template
		}

		var rebuild strings.Builder
		if req.Context != nil {
			// TODO: context is deprecated, at some point the context logic within this conditional should be removed
			prevCtx, err := loaded.runner.Decode(c.Request.Context(), req.Context)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}

			// Remove leading spaces from prevCtx if present
			prevCtx = strings.TrimPrefix(prevCtx, " ")
			rebuild.WriteString(prevCtx)
		}
		p, err := model.Prompt(PromptVars{
			System: req.System,
			Prompt: req.Prompt,
			First:  len(req.Context) == 0,
		})
225
226
227
228
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
Bruce MacDonald's avatar
Bruce MacDonald committed
229
230
		rebuild.WriteString(p)
		prompt = rebuild.String()
Bruce MacDonald's avatar
Bruce MacDonald committed
231
232
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
233
	ch := make(chan any)
Bruce MacDonald's avatar
Bruce MacDonald committed
234
	var generated strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
235
236
237
	go func() {
		defer close(ch)

Bruce MacDonald's avatar
Bruce MacDonald committed
238
239
		fn := func(r llm.PredictResult) {
			// Update model expiration
Bruce MacDonald's avatar
Bruce MacDonald committed
240
241
242
			loaded.expireAt = time.Now().Add(sessionDuration)
			loaded.expireTimer.Reset(sessionDuration)

Bruce MacDonald's avatar
Bruce MacDonald committed
243
244
245
246
			// Build up the full response
			if _, err := generated.WriteString(r.Content); err != nil {
				ch <- gin.H{"error": err.Error()}
				return
Bruce MacDonald's avatar
Bruce MacDonald committed
247
248
			}

Bruce MacDonald's avatar
Bruce MacDonald committed
249
			resp := api.GenerateResponse{
250
				Model:     req.Model,
251
				CreatedAt: time.Now().UTC(),
252
253
				Done:      r.Done,
				Response:  r.Content,
Bruce MacDonald's avatar
Bruce MacDonald committed
254
255
256
257
258
259
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
Bruce MacDonald's avatar
Bruce MacDonald committed
260
261
			}

262
263
264
265
266
267
268
269
270
271
272
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)

				if !req.Raw {
					embd, err := loaded.runner.Encode(c.Request.Context(), prompt+generated.String())
					if err != nil {
						ch <- gin.H{"error": err.Error()}
						return
					}
					resp.Context = embd
Bruce MacDonald's avatar
Bruce MacDonald committed
273
274
275
276
				}
			}

			ch <- resp
Bruce MacDonald's avatar
Bruce MacDonald committed
277
278
		}

Bruce MacDonald's avatar
Bruce MacDonald committed
279
280
		// Start prediction
		predictReq := llm.PredictOpts{
281
282
283
			Prompt: prompt,
			Format: req.Format,
			Images: req.Images,
Bruce MacDonald's avatar
Bruce MacDonald committed
284
285
		}
		if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
286
287
288
289
290
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
291
292
		// Accumulate responses into the final response
		var final api.GenerateResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
293
		var sb strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
294
		for resp := range ch {
295
296
297
298
299
300
301
302
303
304
305
306
307
308
			switch r := resp.(type) {
			case api.GenerateResponse:
				sb.WriteString(r.Response)
				final = r
			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 response"})
					return
				}
			default:
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error"})
Bruce MacDonald's avatar
Bruce MacDonald committed
309
310
311
				return
			}
		}
312
313
314

		final.Response = sb.String()
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
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
		return
	}

	streamResponse(c, ch)
}

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

	var req api.EmbeddingRequest
	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()})
		return
	}

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

Bruce MacDonald's avatar
Bruce MacDonald committed
341
342
	sessionDuration := defaultSessionDuration
	_, err = load(c, req.Model, req.Options, sessionDuration)
Bruce MacDonald's avatar
Bruce MacDonald committed
343
	if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
344
345
346
347
348
349
350
351
352
		var pErr *fs.PathError
		switch {
		case errors.As(err, &pErr):
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
		case errors.Is(err, api.ErrInvalidOpts):
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
Bruce MacDonald's avatar
Bruce MacDonald committed
353
354
355
		return
	}

356
	if !loaded.Options.EmbeddingOnly {
Bruce MacDonald's avatar
Bruce MacDonald committed
357
358
359
360
		c.JSON(http.StatusBadRequest, gin.H{"error": "embedding option must be set to true"})
		return
	}

361
	embedding, err := loaded.runner.Embedding(c.Request.Context(), req.Prompt)
Bruce MacDonald's avatar
Bruce MacDonald committed
362
363
364
365
366
367
368
369
370
371
372
373
	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)
}

374
func PullModelHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
375
	var req api.PullRequest
Michael Yang's avatar
Michael Yang committed
376
377
378
379
380
381
382
	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
383
384
385
		return
	}

386
387
388
389
390
	if req.Name == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
		return
	}

391
392
393
	ch := make(chan any)
	go func() {
		defer close(ch)
394
395
		fn := func(r api.ProgressResponse) {
			ch <- r
396
		}
397

398
399
400
401
		regOpts := &RegistryOptions{
			Insecure: req.Insecure,
		}

402
403
404
405
		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
406
			ch <- gin.H{"error": err.Error()}
407
408
409
		}
	}()

410
411
412
413
414
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

415
416
417
	streamResponse(c, ch)
}

418
func PushModelHandler(c *gin.Context) {
419
	var req api.PushRequest
Michael Yang's avatar
Michael Yang committed
420
421
422
423
424
425
426
	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
427
428
		return
	}
Michael Yang's avatar
Michael Yang committed
429

430
431
432
433
434
	if req.Name == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
		return
	}

435
436
437
	ch := make(chan any)
	go func() {
		defer close(ch)
438
439
		fn := func(r api.ProgressResponse) {
			ch <- r
440
		}
441

442
443
444
445
		regOpts := &RegistryOptions{
			Insecure: req.Insecure,
		}

Michael Yang's avatar
Michael Yang committed
446
447
448
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

449
		if err := PushModel(ctx, req.Name, regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
450
			ch <- gin.H{"error": err.Error()}
451
452
453
		}
	}()

454
455
456
457
458
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

459
460
461
	streamResponse(c, ch)
}

462
func CreateModelHandler(c *gin.Context) {
463
	var req api.CreateRequest
Michael Yang's avatar
Michael Yang committed
464
465
466
467
468
469
470
	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
471
		return
472
473
	}

Michael Yang's avatar
Michael Yang committed
474
475
	if req.Name == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
476
477
478
		return
	}

479
480
	if err := ParseModelPath(req.Name).Validate(); err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
481
482
483
		return
	}

Michael Yang's avatar
Michael Yang committed
484
485
	if req.Path == "" && req.Modelfile == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
Michael Yang's avatar
Michael Yang committed
486
487
		return
	}
Michael Yang's avatar
Michael Yang committed
488
489
490

	var modelfile io.Reader = strings.NewReader(req.Modelfile)
	if req.Path != "" && req.Modelfile == "" {
491
		mf, err := os.Open(req.Path)
Michael Yang's avatar
Michael Yang committed
492
493
494
495
		if err != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
			return
		}
496
		defer mf.Close()
Michael Yang's avatar
Michael Yang committed
497

498
		modelfile = mf
Michael Yang's avatar
Michael Yang committed
499
	}
Michael Yang's avatar
Michael Yang committed
500
501
502
503
504
505
506

	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
507
	ch := make(chan any)
Michael Yang's avatar
Michael Yang committed
508
509
	go func() {
		defer close(ch)
510
511
		fn := func(resp api.ProgressResponse) {
			ch <- resp
512
513
		}

514
515
516
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

517
		if err := CreateModel(ctx, req.Name, filepath.Dir(req.Path), commands, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
518
			ch <- gin.H{"error": err.Error()}
519
		}
Michael Yang's avatar
Michael Yang committed
520
	}()
Michael Yang's avatar
Michael Yang committed
521

522
523
524
525
526
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

Michael Yang's avatar
Michael Yang committed
527
	streamResponse(c, ch)
Bruce MacDonald's avatar
Bruce MacDonald committed
528
529
}

530
531
func DeleteModelHandler(c *gin.Context) {
	var req api.DeleteRequest
Michael Yang's avatar
Michael Yang committed
532
533
534
535
536
537
538
	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()})
539
540
541
		return
	}

542
543
544
545
546
	if req.Name == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
		return
	}

547
548
549
550
	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 {
551
552
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
553
554
		return
	}
Michael Yang's avatar
Michael Yang committed
555
556
557
558
559
560
561
562
563
564
565
566

	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
	}

567
	c.JSON(http.StatusOK, nil)
568
569
}

Patrick Devine's avatar
Patrick Devine committed
570
571
func ShowModelHandler(c *gin.Context) {
	var req api.ShowRequest
Michael Yang's avatar
Michael Yang committed
572
573
574
575
576
577
578
	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
579
580
581
		return
	}

582
583
584
585
586
	if req.Name == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
		return
	}

Patrick Devine's avatar
Patrick Devine committed
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
	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
	}

Patrick Devine's avatar
Patrick Devine committed
606
607
608
609
610
611
612
613
	modelDetails := api.ModelDetails{
		Format:            model.Config.ModelFormat,
		Family:            model.Config.ModelFamily,
		Families:          model.Config.ModelFamilies,
		ParameterSize:     model.Config.ModelType,
		QuantizationLevel: model.Config.FileType,
	}

Patrick Devine's avatar
Patrick Devine committed
614
615
616
617
	resp := &api.ShowResponse{
		License:  strings.Join(model.License, "\n"),
		System:   model.System,
		Template: model.Template,
Patrick Devine's avatar
Patrick Devine committed
618
		Details:  modelDetails,
Patrick Devine's avatar
Patrick Devine committed
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
	}

	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
}

660
func ListModelsHandler(c *gin.Context) {
661
	models := make([]api.ModelResponse, 0)
Patrick Devine's avatar
Patrick Devine committed
662
663
664
665
666
	fp, err := GetManifestPath()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
667

Patrick Devine's avatar
Patrick Devine committed
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
	modelResponse := func(modelName string) (api.ModelResponse, error) {
		model, err := GetModel(modelName)
		if err != nil {
			return api.ModelResponse{}, err
		}

		modelDetails := api.ModelDetails{
			Format:            model.Config.ModelFormat,
			Family:            model.Config.ModelFamily,
			Families:          model.Config.ModelFamilies,
			ParameterSize:     model.Config.ModelType,
			QuantizationLevel: model.Config.FileType,
		}

		return api.ModelResponse{
			Name:    model.ShortName,
			Size:    model.Size,
			Digest:  model.Digest,
			Details: modelDetails,
		}, nil
	}

Michael Yang's avatar
Michael Yang committed
690
	walkFunc := func(path string, info os.FileInfo, _ error) error {
Patrick Devine's avatar
Patrick Devine committed
691
		if !info.IsDir() {
Michael Yang's avatar
Michael Yang committed
692
693
694
			dir, file := filepath.Split(path)
			dir = strings.Trim(strings.TrimPrefix(dir, fp), string(os.PathSeparator))
			tag := strings.Join([]string{dir, file}, ":")
695

Patrick Devine's avatar
Patrick Devine committed
696
			resp, err := modelResponse(tag)
Patrick Devine's avatar
Patrick Devine committed
697
			if err != nil {
698
699
				log.Printf("skipping file: %s", fp)
				return nil
Patrick Devine's avatar
Patrick Devine committed
700
			}
Michael Yang's avatar
Michael Yang committed
701

Patrick Devine's avatar
Patrick Devine committed
702
703
			resp.ModifiedAt = info.ModTime()
			models = append(models, resp)
Patrick Devine's avatar
Patrick Devine committed
704
		}
Michael Yang's avatar
Michael Yang committed
705

Patrick Devine's avatar
Patrick Devine committed
706
		return nil
Michael Yang's avatar
Michael Yang committed
707
708
709
	}

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

Michael Yang's avatar
Michael Yang committed
714
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
715
716
}

Patrick Devine's avatar
Patrick Devine committed
717
718
func CopyModelHandler(c *gin.Context) {
	var req api.CopyRequest
Michael Yang's avatar
Michael Yang committed
719
720
721
722
723
724
725
	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
726
727
728
		return
	}

729
730
731
732
733
	if req.Source == "" || req.Destination == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
		return
	}

734
735
736
737
738
	if err := ParseModelPath(req.Destination).Validate(); err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Patrick Devine's avatar
Patrick Devine committed
739
740
741
742
743
744
745
746
747
748
	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
749
func HeadBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
750
751
752
753
754
755
756
757
758
759
760
	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
761
	c.Status(http.StatusOK)
Michael Yang's avatar
Michael Yang committed
762
763
764
}

func CreateBlobHandler(c *gin.Context) {
765
	layer, err := NewLayer(c.Request.Body, "")
Michael Yang's avatar
Michael Yang committed
766
767
768
769
770
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

771
772
	if layer.Digest != c.Param("digest") {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("digest mismatch, expected %q, got %q", c.Param("digest"), layer.Digest)})
Michael Yang's avatar
Michael Yang committed
773
774
775
		return
	}

776
	if _, err := layer.Commit(); err != nil {
Michael Yang's avatar
Michael Yang committed
777
778
779
780
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
781
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
782
783
}

Michael Yang's avatar
Michael Yang committed
784
785
786
787
788
789
var defaultAllowOrigins = []string{
	"localhost",
	"127.0.0.1",
	"0.0.0.0",
}

790
791
792
793
794
func NewServer() (*Server, error) {
	workDir, err := os.MkdirTemp("", "ollama")
	if err != nil {
		return nil, err
	}
795

796
797
798
799
	return &Server{
		WorkDir: workDir,
	}, nil
}
800

801
802
803
804
func (s *Server) GenerateRoutes() http.Handler {
	var origins []string
	if o := os.Getenv("OLLAMA_ORIGINS"); o != "" {
		origins = strings.Split(o, ",")
805
806
	}

Michael Yang's avatar
Michael Yang committed
807
808
	config := cors.DefaultConfig()
	config.AllowWildcard = true
Michael Yang's avatar
Michael Yang committed
809

810
	config.AllowOrigins = origins
Michael Yang's avatar
Michael Yang committed
811
812
813
814
815
816
817
818
	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
819

Bruce MacDonald's avatar
Bruce MacDonald committed
820
	r := gin.Default()
821
822
823
	r.Use(
		cors.New(config),
		func(c *gin.Context) {
824
			c.Set("workDir", s.WorkDir)
825
826
827
			c.Next()
		},
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
828

829
830
	r.POST("/api/pull", PullModelHandler)
	r.POST("/api/generate", GenerateHandler)
Bruce MacDonald's avatar
Bruce MacDonald committed
831
	r.POST("/api/chat", ChatHandler)
Bruce MacDonald's avatar
Bruce MacDonald committed
832
	r.POST("/api/embeddings", EmbeddingHandler)
833
834
	r.POST("/api/create", CreateModelHandler)
	r.POST("/api/push", PushModelHandler)
Patrick Devine's avatar
Patrick Devine committed
835
	r.POST("/api/copy", CopyModelHandler)
836
	r.DELETE("/api/delete", DeleteModelHandler)
Patrick Devine's avatar
Patrick Devine committed
837
	r.POST("/api/show", ShowModelHandler)
Michael Yang's avatar
Michael Yang committed
838
	r.POST("/api/blobs/:digest", CreateBlobHandler)
Michael Yang's avatar
Michael Yang committed
839
	r.HEAD("/api/blobs/:digest", HeadBlobHandler)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
840

Michael Yang's avatar
Michael Yang committed
841
842
843
844
845
846
	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
847
848
849
		r.Handle(method, "/api/version", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{"version": version.Version})
		})
Michael Yang's avatar
Michael Yang committed
850
851
	}

852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
	return r
}

func Serve(ln net.Listener) error {
	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
		}
	}

	s, err := NewServer()
	if err != nil {
		return err
	}
	r := s.GenerateRoutes()

Michael Yang's avatar
Michael Yang committed
878
	log.Printf("Listening on %s (version %s)", ln.Addr(), version.Version)
879
	srvr := &http.Server{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
880
881
882
		Handler: r,
	}

883
884
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
885
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
886
887
	go func() {
		<-signals
888
889
		if loaded.runner != nil {
			loaded.runner.Close()
890
		}
891
		os.RemoveAll(s.WorkDir)
892
893
894
		os.Exit(0)
	}()

895
896
897
898
	if err := llm.Init(s.WorkDir); err != nil {
		return fmt.Errorf("unable to initialize llm library %w", err)
	}
	if runtime.GOOS == "linux" { // TODO - windows too
899
		// check compatibility to log warnings
900
		if _, err := gpu.CheckVRAM(); err != nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
901
			log.Print(err.Error())
902
903
904
		}
	}

905
	return srvr.Serve(ln)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
906
}
Michael Yang's avatar
Michael Yang committed
907

908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
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
933
func streamResponse(c *gin.Context, ch chan any) {
934
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
935
936
937
938
939
940
941
942
	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
943
			log.Printf("streamResponse: json.Marshal failed with %s", err)
Michael Yang's avatar
Michael Yang committed
944
945
946
			return false
		}

947
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
948
949
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
950
			log.Printf("streamResponse: w.Write failed with %s", err)
Michael Yang's avatar
Michael Yang committed
951
952
953
954
955
956
			return false
		}

		return true
	})
}
Bruce MacDonald's avatar
Bruce MacDonald committed
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001

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

	checkpointStart := time.Now()

	var req api.ChatRequest
	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()})
		return
	}

	// validate the request
	switch {
	case req.Model == "":
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
	case len(req.Format) > 0 && req.Format != "json":
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
		return
	}

	sessionDuration := defaultSessionDuration
	model, err := load(c, req.Model, req.Options, sessionDuration)
	if err != nil {
		var pErr *fs.PathError
		switch {
		case errors.As(err, &pErr):
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
		case errors.Is(err, api.ErrInvalidOpts):
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

	// an empty request loads the model
	if len(req.Messages) == 0 {
1002
		c.JSON(http.StatusOK, api.ChatResponse{CreatedAt: time.Now().UTC(), Model: req.Model, Done: true, Message: api.Message{Role: "assistant"}})
Bruce MacDonald's avatar
Bruce MacDonald committed
1003
1004
1005
1006
1007
		return
	}

	checkpointLoaded := time.Now()

1008
	prompt, images, err := model.ChatPrompt(req.Messages)
Bruce MacDonald's avatar
Bruce MacDonald committed
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	ch := make(chan any)

	go func() {
		defer close(ch)

		fn := func(r llm.PredictResult) {
			// Update model expiration
			loaded.expireAt = time.Now().Add(sessionDuration)
			loaded.expireTimer.Reset(sessionDuration)

			resp := api.ChatResponse{
1025
				Model:     req.Model,
1026
				CreatedAt: time.Now().UTC(),
1027
				Message:   api.Message{Role: "assistant", Content: r.Content},
Bruce MacDonald's avatar
Bruce MacDonald committed
1028
1029
1030
1031
1032
1033
1034
1035
1036
				Done:      r.Done,
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}

1037
1038
1039
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
Bruce MacDonald's avatar
Bruce MacDonald committed
1040
1041
1042
1043
1044
1045
1046
			}

			ch <- resp
		}

		// Start prediction
		predictReq := llm.PredictOpts{
1047
1048
1049
			Prompt: prompt,
			Format: req.Format,
			Images: images,
Bruce MacDonald's avatar
Bruce MacDonald committed
1050
1051
1052
1053
1054
1055
1056
		}
		if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
1057
1058
		// Accumulate responses into the final response
		var final api.ChatResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
1059
1060
		var sb strings.Builder
		for resp := range ch {
1061
1062
			switch r := resp.(type) {
			case api.ChatResponse:
1063
				sb.WriteString(r.Message.Content)
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
				final = r
			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 response"})
					return
				}
			default:
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error"})
				return
Bruce MacDonald's avatar
Bruce MacDonald committed
1076
1077
			}
		}
1078

1079
		final.Message = api.Message{Role: "assistant", Content: sb.String()}
1080
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
1081
1082
1083
1084
1085
		return
	}

	streamResponse(c, ch)
}