routes.go 33.2 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"
10
	"log/slog"
11
	"math"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
12
13
	"net"
	"net/http"
14
	"net/netip"
15
	"os"
16
	"os/signal"
Michael Yang's avatar
Michael Yang committed
17
	"path/filepath"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
18
	"reflect"
19
	"runtime"
20
	"strconv"
Michael Yang's avatar
Michael Yang committed
21
	"strings"
Michael Yang's avatar
Michael Yang committed
22
	"sync"
23
	"syscall"
24
	"time"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
25

Michael Yang's avatar
Michael Yang committed
26
	"github.com/gin-contrib/cors"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
27
	"github.com/gin-gonic/gin"
28
	"golang.org/x/exp/slices"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
29

30
31
32
33
34
35
	"github.com/ollama/ollama/api"
	"github.com/ollama/ollama/gpu"
	"github.com/ollama/ollama/llm"
	"github.com/ollama/ollama/openai"
	"github.com/ollama/ollama/parser"
	"github.com/ollama/ollama/version"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
36
37
)

Michael Yang's avatar
Michael Yang committed
38
39
var mode string = gin.DebugMode

40
type Server struct {
41
	addr net.Addr
42
43
}

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

59
	runner llm.LLM
Michael Yang's avatar
Michael Yang committed
60
61
62

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

64
65
	*Model
	*api.Options
Michael Yang's avatar
Michael Yang committed
66
67
}

68
69
var defaultSessionDuration = 5 * time.Minute

Bruce MacDonald's avatar
Bruce MacDonald committed
70
// 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
Michael Yang's avatar
Michael Yang committed
71
func load(c *gin.Context, model *Model, opts *api.Options, sessionDuration time.Duration) error {
72
73
74
75
76
77
78
	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 {
79
			slog.Info("changing loaded model")
80
81
82
83
			loaded.runner.Close()
			loaded.runner = nil
			loaded.Model = nil
			loaded.Options = nil
Michael Yang's avatar
Michael Yang committed
84
		}
Michael Yang's avatar
Michael Yang committed
85

Daniel Hiltgen's avatar
Daniel Hiltgen committed
86
		llmRunner, err := llm.New(model.ModelPath, model.AdapterPaths, model.ProjectorPaths, opts)
Michael Yang's avatar
Michael Yang committed
87
		if err != nil {
88
89
90
			// 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
91
			if errors.Is(llm.ErrUnsupportedFormat, err) || strings.Contains(err.Error(), "failed to load model") {
92
93
94
				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)
			}

95
			return err
Michael Yang's avatar
Michael Yang committed
96
97
		}

98
99
		loaded.Model = model
		loaded.runner = llmRunner
Michael Yang's avatar
Michael Yang committed
100
		loaded.Options = opts
Michael Yang's avatar
Michael Yang committed
101
	}
102

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
105
106
107
108
	if loaded.expireTimer == nil {
		loaded.expireTimer = time.AfterFunc(sessionDuration, func() {
			loaded.mu.Lock()
			defer loaded.mu.Unlock()
Michael Yang's avatar
Michael Yang committed
109

Jeffrey Morgan's avatar
Jeffrey Morgan committed
110
			if time.Now().Before(loaded.expireAt) {
Michael Yang's avatar
Michael Yang committed
111
112
113
				return
			}

114
115
			if loaded.runner != nil {
				loaded.runner.Close()
Michael Yang's avatar
Michael Yang committed
116
117
			}

118
119
120
			loaded.runner = nil
			loaded.Model = nil
			loaded.Options = nil
Michael Yang's avatar
Michael Yang committed
121
		})
Michael Yang's avatar
Michael Yang committed
122
	}
123

Jeffrey Morgan's avatar
Jeffrey Morgan committed
124
	loaded.expireTimer.Reset(sessionDuration)
125
126
127
128
129
130
131
132
133
134
135
136
137
138
	return nil
}

func modelOptions(model *Model, requestOpts map[string]interface{}) (api.Options, error) {
	opts := api.DefaultOptions()
	if err := opts.FromMap(model.Options); err != nil {
		return api.Options{}, err
	}

	if err := opts.FromMap(requestOpts); err != nil {
		return api.Options{}, err
	}

	return opts, nil
Bruce MacDonald's avatar
Bruce MacDonald committed
139
140
}

141
142
143
144
145
146
func isSupportedImageType(image []byte) bool {
	contentType := http.DetectContentType(image)
	allowedTypes := []string{"image/jpeg", "image/jpg", "image/png"}
	return slices.Contains(allowedTypes, contentType)
}

Bruce MacDonald's avatar
Bruce MacDonald committed
147
148
149
150
151
152
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
	err := c.ShouldBindJSON(&req)
Patrick Devine's avatar
Patrick Devine committed
154

Michael Yang's avatar
Michael Yang committed
155
156
157
158
159
160
	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
161
162
163
		return
	}

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

177
178
179
180
181
182
183
	for _, img := range req.Images {
		if !isSupportedImageType(img) {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "unsupported image format"})
			return
		}
	}

184
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
185
	if err != nil {
186
		var pErr *fs.PathError
187
		if errors.As(err, &pErr) {
188
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
189
190
191
192
193
194
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

195
	if model.IsEmbedding() {
196
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "embedding models do not support generate"})
197
198
199
		return
	}

200
201
202
	opts, err := modelOptions(model, req.Options)
	if err != nil {
		if errors.Is(err, api.ErrInvalidOpts) {
Bruce MacDonald's avatar
Bruce MacDonald committed
203
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
204
			return
205
		}
206
207
208
209
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

210
211
	var sessionDuration time.Duration
	if req.KeepAlive == nil {
212
		sessionDuration = getDefaultSessionDuration()
213
214
215
216
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

Michael Yang's avatar
Michael Yang committed
217
	if err := load(c, model, &opts, sessionDuration); err != nil {
218
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
219
220
221
		return
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
222
	// an empty request loads the model
223
224
	// note: for a short while template was used in lieu
	// of `raw` mode so we need to check for it too
Bruce MacDonald's avatar
Bruce MacDonald committed
225
	if req.Prompt == "" && req.Template == "" && req.System == "" {
226
		c.JSON(http.StatusOK, api.GenerateResponse{
227
228
			CreatedAt: time.Now().UTC(),
			Model:     req.Model,
Michael Yang's avatar
Michael Yang committed
229
230
			Done:      true,
		})
Bruce MacDonald's avatar
Bruce MacDonald committed
231
232
233
234
235
		return
	}

	checkpointLoaded := time.Now()

Bruce MacDonald's avatar
Bruce MacDonald committed
236
237
238
239
240
	var prompt string
	switch {
	case req.Raw:
		prompt = req.Prompt
	case req.Prompt != "":
241
242
		if req.Template == "" {
			req.Template = model.Template
Bruce MacDonald's avatar
Bruce MacDonald committed
243
244
		}

245
246
247
248
249
250
251
252
253
		if req.System == "" {
			req.System = model.System
		}

		slog.Debug("generate handler", "prompt", req.Prompt)
		slog.Debug("generate handler", "template", req.Template)
		slog.Debug("generate handler", "system", req.System)

		var sb strings.Builder
Michael Yang's avatar
Michael Yang committed
254
255
256
257
258
259
260
261
262
263
264
265
266
		for i := range req.Images {
			fmt.Fprintf(&sb, "[img-%d] ", i)
		}

		sb.WriteString(req.Prompt)

		p, err := Prompt(req.Template, req.System, sb.String(), "", true)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		sb.Reset()
Bruce MacDonald's avatar
Bruce MacDonald committed
267
		if req.Context != nil {
268
			prev, err := loaded.runner.Decode(c.Request.Context(), req.Context)
Bruce MacDonald's avatar
Bruce MacDonald committed
269
270
271
272
273
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}

274
			sb.WriteString(prev)
275
276
		}

277
278
279
		sb.WriteString(p)

		prompt = sb.String()
Bruce MacDonald's avatar
Bruce MacDonald committed
280
281
	}

Michael Yang's avatar
Michael Yang committed
282
	slog.Debug("generate handler", "prompt", prompt)
283

Bruce MacDonald's avatar
Bruce MacDonald committed
284
	ch := make(chan any)
Bruce MacDonald's avatar
Bruce MacDonald committed
285
	var generated strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
286
287
288
	go func() {
		defer close(ch)

Bruce MacDonald's avatar
Bruce MacDonald committed
289
290
		fn := func(r llm.PredictResult) {
			// Update model expiration
Bruce MacDonald's avatar
Bruce MacDonald committed
291
292
293
			loaded.expireAt = time.Now().Add(sessionDuration)
			loaded.expireTimer.Reset(sessionDuration)

Bruce MacDonald's avatar
Bruce MacDonald committed
294
295
296
297
			// 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
298
299
			}

Bruce MacDonald's avatar
Bruce MacDonald committed
300
			resp := api.GenerateResponse{
301
				Model:     req.Model,
302
				CreatedAt: time.Now().UTC(),
303
304
				Done:      r.Done,
				Response:  r.Content,
Bruce MacDonald's avatar
Bruce MacDonald committed
305
306
307
308
309
310
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
Bruce MacDonald's avatar
Bruce MacDonald committed
311
312
			}

313
314
315
316
317
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)

				if !req.Raw {
318
					p, err := Prompt(req.Template, req.System, req.Prompt, generated.String(), false)
319
					if err != nil {
320
						c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
321
322
						return
					}
323
324
325

					// TODO (jmorganca): encode() should not strip special tokens
					tokens, err := loaded.runner.Encode(c.Request.Context(), p)
326
327
328
329
					if err != nil {
						ch <- gin.H{"error": err.Error()}
						return
					}
330
331

					resp.Context = append(req.Context, tokens...)
Bruce MacDonald's avatar
Bruce MacDonald committed
332
333
334
335
				}
			}

			ch <- resp
Bruce MacDonald's avatar
Bruce MacDonald committed
336
337
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
338
		var images []llm.ImageData
Michael Yang's avatar
Michael Yang committed
339
		for i := range req.Images {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
340
341
342
343
			images = append(images, llm.ImageData{
				ID:   i,
				Data: req.Images[i],
			})
Michael Yang's avatar
Michael Yang committed
344
345
		}

Bruce MacDonald's avatar
Bruce MacDonald committed
346
347
		// Start prediction
		predictReq := llm.PredictOpts{
348
349
			Prompt:  prompt,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
350
			Images:  images,
351
			Options: opts,
Bruce MacDonald's avatar
Bruce MacDonald committed
352
353
		}
		if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
354
355
356
357
358
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
359
360
		// Accumulate responses into the final response
		var final api.GenerateResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
361
		var sb strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
362
		for resp := range ch {
363
364
365
366
367
368
369
370
371
372
373
374
375
376
			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
377
378
379
				return
			}
		}
380
381
382

		final.Response = sb.String()
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
383
384
385
386
387
388
		return
	}

	streamResponse(c, ch)
}

389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
func getDefaultSessionDuration() time.Duration {
	if t, exists := os.LookupEnv("OLLAMA_KEEP_ALIVE"); exists {
		v, err := strconv.Atoi(t)
		if err != nil {
			d, err := time.ParseDuration(t)
			if err != nil {
				return defaultSessionDuration
			}

			if d < 0 {
				return time.Duration(math.MaxInt64)
			}

			return d
		}

		d := time.Duration(v) * time.Second
		if d < 0 {
			return time.Duration(math.MaxInt64)
		}
		return d
	}

	return defaultSessionDuration
}

415
func EmbeddingsHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
	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
	}

435
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
436
	if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
437
		var pErr *fs.PathError
438
		if errors.As(err, &pErr) {
Bruce MacDonald's avatar
Bruce MacDonald committed
439
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
440
441
442
443
444
445
446
447
448
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	opts, err := modelOptions(model, req.Options)
	if err != nil {
		if errors.Is(err, api.ErrInvalidOpts) {
Bruce MacDonald's avatar
Bruce MacDonald committed
449
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
450
			return
Bruce MacDonald's avatar
Bruce MacDonald committed
451
		}
452
453
454
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
455
456
457

	var sessionDuration time.Duration
	if req.KeepAlive == nil {
458
		sessionDuration = getDefaultSessionDuration()
459
460
461
462
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

Michael Yang's avatar
Michael Yang committed
463
	if err := load(c, model, &opts, sessionDuration); err != nil {
464
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
465
466
467
		return
	}

468
469
470
	// an empty request loads the model
	if req.Prompt == "" {
		c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: []float64{}})
Bruce MacDonald's avatar
Bruce MacDonald committed
471
472
473
		return
	}

474
	embedding, err := loaded.runner.Embedding(c.Request.Context(), req.Prompt)
Bruce MacDonald's avatar
Bruce MacDonald committed
475
	if err != nil {
476
		slog.Info(fmt.Sprintf("embedding generation failed: %v", err))
Bruce MacDonald's avatar
Bruce MacDonald committed
477
478
479
480
481
482
483
484
485
486
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
		return
	}

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

487
func PullModelHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
488
	var req api.PullRequest
Michael Yang's avatar
Michael Yang committed
489
490
491
492
493
494
495
	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
496
497
498
		return
	}

Michael Yang's avatar
Michael Yang committed
499
500
501
502
503
504
505
	var model string
	if req.Model != "" {
		model = req.Model
	} else if req.Name != "" {
		model = req.Name
	} else {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
506
507
508
		return
	}

509
510
511
	ch := make(chan any)
	go func() {
		defer close(ch)
512
513
		fn := func(r api.ProgressResponse) {
			ch <- r
514
		}
515

Michael Yang's avatar
Michael Yang committed
516
		regOpts := &registryOptions{
517
518
519
			Insecure: req.Insecure,
		}

520
521
522
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
523
		if err := PullModel(ctx, model, regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
524
			ch <- gin.H{"error": err.Error()}
525
526
527
		}
	}()

528
529
530
531
532
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

533
534
535
	streamResponse(c, ch)
}

536
func PushModelHandler(c *gin.Context) {
537
	var req api.PushRequest
Michael Yang's avatar
Michael Yang committed
538
539
540
541
542
543
544
	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
545
546
		return
	}
Michael Yang's avatar
Michael Yang committed
547

Michael Yang's avatar
Michael Yang committed
548
549
550
551
552
553
554
	var model string
	if req.Model != "" {
		model = req.Model
	} else if req.Name != "" {
		model = req.Name
	} else {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
555
556
557
		return
	}

558
559
560
	ch := make(chan any)
	go func() {
		defer close(ch)
561
562
		fn := func(r api.ProgressResponse) {
			ch <- r
563
		}
564

Michael Yang's avatar
Michael Yang committed
565
		regOpts := &registryOptions{
566
567
568
			Insecure: req.Insecure,
		}

Michael Yang's avatar
Michael Yang committed
569
570
571
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
572
		if err := PushModel(ctx, model, regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
573
			ch <- gin.H{"error": err.Error()}
574
575
576
		}
	}()

577
578
579
580
581
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

582
583
584
	streamResponse(c, ch)
}

585
func CreateModelHandler(c *gin.Context) {
586
	var req api.CreateRequest
Michael Yang's avatar
Michael Yang committed
587
588
589
590
591
592
593
	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
594
		return
595
596
	}

Michael Yang's avatar
Michael Yang committed
597
598
599
600
601
602
603
	var model string
	if req.Model != "" {
		model = req.Model
	} else if req.Name != "" {
		model = req.Name
	} else {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
604
605
606
		return
	}

Michael Yang's avatar
Michael Yang committed
607
	if err := ParseModelPath(model).Validate(); err != nil {
608
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
609
610
611
		return
	}

Michael Yang's avatar
Michael Yang committed
612
613
	if req.Path == "" && req.Modelfile == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
Michael Yang's avatar
Michael Yang committed
614
615
		return
	}
Michael Yang's avatar
Michael Yang committed
616
617
618

	var modelfile io.Reader = strings.NewReader(req.Modelfile)
	if req.Path != "" && req.Modelfile == "" {
619
		mf, err := os.Open(req.Path)
Michael Yang's avatar
Michael Yang committed
620
621
622
623
		if err != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
			return
		}
624
		defer mf.Close()
Michael Yang's avatar
Michael Yang committed
625

626
		modelfile = mf
Michael Yang's avatar
Michael Yang committed
627
	}
Michael Yang's avatar
Michael Yang committed
628
629
630
631
632
633
634

	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
635
	ch := make(chan any)
Michael Yang's avatar
Michael Yang committed
636
637
	go func() {
		defer close(ch)
638
639
		fn := func(resp api.ProgressResponse) {
			ch <- resp
640
641
		}

642
643
644
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
645
		if err := CreateModel(ctx, model, filepath.Dir(req.Path), commands, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
646
			ch <- gin.H{"error": err.Error()}
647
		}
Michael Yang's avatar
Michael Yang committed
648
	}()
Michael Yang's avatar
Michael Yang committed
649

650
651
652
653
654
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

Michael Yang's avatar
Michael Yang committed
655
	streamResponse(c, ch)
Bruce MacDonald's avatar
Bruce MacDonald committed
656
657
}

658
659
func DeleteModelHandler(c *gin.Context) {
	var req api.DeleteRequest
Michael Yang's avatar
Michael Yang committed
660
661
662
663
664
665
666
	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()})
667
668
669
		return
	}

Michael Yang's avatar
Michael Yang committed
670
671
672
673
674
675
676
	var model string
	if req.Model != "" {
		model = req.Model
	} else if req.Name != "" {
		model = req.Name
	} else {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
677
678
679
		return
	}

Michael Yang's avatar
Michael Yang committed
680
	if err := DeleteModel(model); err != nil {
681
		if os.IsNotExist(err) {
Michael Yang's avatar
Michael Yang committed
682
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", model)})
683
		} else {
684
685
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
686
687
		return
	}
Michael Yang's avatar
Michael Yang committed
688
689
690
691
692
693
694
695
696
697
698
699

	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
	}

700
	c.JSON(http.StatusOK, nil)
701
702
}

Patrick Devine's avatar
Patrick Devine committed
703
704
func ShowModelHandler(c *gin.Context) {
	var req api.ShowRequest
Michael Yang's avatar
Michael Yang committed
705
706
707
708
709
710
711
	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
712
713
714
		return
	}

Michael Yang's avatar
Michael Yang committed
715
	if req.Model != "" {
Michael Yang's avatar
Michael Yang committed
716
		// noop
Michael Yang's avatar
Michael Yang committed
717
	} else if req.Name != "" {
Michael Yang's avatar
Michael Yang committed
718
		req.Model = req.Name
Michael Yang's avatar
Michael Yang committed
719
	} else {
720
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
721
722
723
		return
	}

724
	resp, err := GetModelInfo(req)
Patrick Devine's avatar
Patrick Devine committed
725
726
	if err != nil {
		if os.IsNotExist(err) {
Michael Yang's avatar
Michael Yang committed
727
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
Patrick Devine's avatar
Patrick Devine committed
728
729
730
731
732
733
734
735
736
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

	c.JSON(http.StatusOK, resp)
}

737
738
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
	model, err := GetModel(req.Model)
Patrick Devine's avatar
Patrick Devine committed
739
740
741
742
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
743
	modelDetails := api.ModelDetails{
744
		ParentModel:       model.ParentModel,
Patrick Devine's avatar
Patrick Devine committed
745
746
747
748
749
750
751
		Format:            model.Config.ModelFormat,
		Family:            model.Config.ModelFamily,
		Families:          model.Config.ModelFamilies,
		ParameterSize:     model.Config.ModelType,
		QuantizationLevel: model.Config.FileType,
	}

752
753
754
755
756
757
758
759
	if req.System != "" {
		model.System = req.System
	}

	if req.Template != "" {
		model.Template = req.Template
	}

760
761
762
763
764
	msgs := make([]api.Message, 0)
	for _, msg := range model.Messages {
		msgs = append(msgs, api.Message{Role: msg.Role, Content: msg.Content})
	}

Patrick Devine's avatar
Patrick Devine committed
765
766
767
768
	resp := &api.ShowResponse{
		License:  strings.Join(model.License, "\n"),
		System:   model.System,
		Template: model.Template,
Patrick Devine's avatar
Patrick Devine committed
769
		Details:  modelDetails,
770
		Messages: msgs,
Patrick Devine's avatar
Patrick Devine committed
771
772
773
774
775
776
777
778
	}

	var params []string
	cs := 30
	for k, v := range model.Options {
		switch val := v.(type) {
		case []interface{}:
			for _, nv := range val {
Patrick Devine's avatar
Patrick Devine committed
779
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
Patrick Devine's avatar
Patrick Devine committed
780
			}
Patrick Devine's avatar
Patrick Devine committed
781
782
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
Patrick Devine's avatar
Patrick Devine committed
783
784
785
786
		}
	}
	resp.Parameters = strings.Join(params, "\n")

787
788
789
790
791
792
793
794
795
796
797
798
799
	for k, v := range req.Options {
		if _, ok := req.Options[k]; ok {
			model.Options[k] = v
		}
	}

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

	resp.Modelfile = mf

Patrick Devine's avatar
Patrick Devine committed
800
801
802
	return resp, nil
}

803
func ListModelsHandler(c *gin.Context) {
804
	models := make([]api.ModelResponse, 0)
805
	manifestsPath, err := GetManifestPath()
Patrick Devine's avatar
Patrick Devine committed
806
807
808
809
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
810

Patrick Devine's avatar
Patrick Devine committed
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
	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{
Michael Yang's avatar
Michael Yang committed
826
			Model:   model.ShortName,
Patrick Devine's avatar
Patrick Devine committed
827
828
829
830
831
832
833
			Name:    model.ShortName,
			Size:    model.Size,
			Digest:  model.Digest,
			Details: modelDetails,
		}, nil
	}

Michael Yang's avatar
Michael Yang committed
834
	walkFunc := func(path string, info os.FileInfo, _ error) error {
Patrick Devine's avatar
Patrick Devine committed
835
		if !info.IsDir() {
836
837
838
839
			path, tag := filepath.Split(path)
			model := strings.Trim(strings.TrimPrefix(path, manifestsPath), string(os.PathSeparator))
			modelPath := strings.Join([]string{model, tag}, ":")
			canonicalModelPath := strings.ReplaceAll(modelPath, string(os.PathSeparator), "/")
840

841
			resp, err := modelResponse(canonicalModelPath)
Patrick Devine's avatar
Patrick Devine committed
842
			if err != nil {
843
				slog.Info(fmt.Sprintf("skipping file: %s", canonicalModelPath))
Michael Yang's avatar
Michael Yang committed
844
				// nolint: nilerr
845
				return nil
Patrick Devine's avatar
Patrick Devine committed
846
			}
Michael Yang's avatar
Michael Yang committed
847

Patrick Devine's avatar
Patrick Devine committed
848
849
			resp.ModifiedAt = info.ModTime()
			models = append(models, resp)
Patrick Devine's avatar
Patrick Devine committed
850
		}
Michael Yang's avatar
Michael Yang committed
851

Patrick Devine's avatar
Patrick Devine committed
852
		return nil
Michael Yang's avatar
Michael Yang committed
853
854
	}

855
	if err := filepath.Walk(manifestsPath, walkFunc); err != nil {
Patrick Devine's avatar
Patrick Devine committed
856
857
858
859
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
860
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
861
862
}

Patrick Devine's avatar
Patrick Devine committed
863
864
func CopyModelHandler(c *gin.Context) {
	var req api.CopyRequest
Michael Yang's avatar
Michael Yang committed
865
866
867
868
869
870
871
	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
872
873
874
		return
	}

875
876
877
878
879
	if req.Source == "" || req.Destination == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
		return
	}

880
881
882
883
884
	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
885
886
887
888
889
890
891
892
893
894
	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
895
func HeadBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
896
897
898
899
900
901
902
903
904
905
906
	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
907
	c.Status(http.StatusOK)
Michael Yang's avatar
Michael Yang committed
908
909
910
}

func CreateBlobHandler(c *gin.Context) {
911
	layer, err := NewLayer(c.Request.Body, "")
Michael Yang's avatar
Michael Yang committed
912
913
914
915
916
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

917
918
	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
919
920
921
		return
	}

922
	if _, err := layer.Commit(); err != nil {
Michael Yang's avatar
Michael Yang committed
923
924
925
926
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
927
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
928
929
}

Michael Yang's avatar
Michael Yang committed
930
931
932
933
934
935
var defaultAllowOrigins = []string{
	"localhost",
	"127.0.0.1",
	"0.0.0.0",
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
func isLocalIP(ip netip.Addr) bool {
	if interfaces, err := net.Interfaces(); err == nil {
		for _, iface := range interfaces {
			addrs, err := iface.Addrs()
			if err != nil {
				continue
			}

			for _, a := range addrs {
				if parsed, _, err := net.ParseCIDR(a.String()); err == nil {
					if parsed.String() == ip.String() {
						return true
					}
				}
			}
		}
	}

	return false
}

957
func allowedHost(host string) bool {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
958
	if host == "" || host == "localhost" {
959
960
961
962
963
964
965
966
		return true
	}

	if hostname, err := os.Hostname(); err == nil && host == hostname {
		return true
	}

	var tlds = []string{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
967
968
969
		"localhost",
		"local",
		"internal",
970
	}
971

Jeffrey Morgan's avatar
Jeffrey Morgan committed
972
	// check if the host is a local TLD
973
974
975
976
977
978
	for _, tld := range tlds {
		if strings.HasSuffix(host, "."+tld) {
			return true
		}
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
979
	return false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
980
}
981

Jeffrey Morgan's avatar
Jeffrey Morgan committed
982
983
984
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
	return func(c *gin.Context) {
		if addr == nil {
985
986
987
988
			c.Next()
			return
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
989
		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
990
991
992
993
994
995
996
997
998
			c.Next()
			return
		}

		host, _, err := net.SplitHostPort(c.Request.Host)
		if err != nil {
			host = c.Request.Host
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
999
		if addr, err := netip.ParseAddr(host); err == nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1000
			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1001
1002
1003
1004
1005
				c.Next()
				return
			}
		}

1006
1007
1008
1009
1010
1011
1012
		if allowedHost(host) {
			c.Next()
			return
		}

		c.AbortWithStatus(http.StatusForbidden)
	}
1013
}
1014

1015
func (s *Server) GenerateRoutes() http.Handler {
Michael Yang's avatar
Michael Yang committed
1016
1017
	config := cors.DefaultConfig()
	config.AllowWildcard = true
1018
	config.AllowBrowserExtensions = true
Michael Yang's avatar
Michael Yang committed
1019

1020
1021
1022
1023
	if allowedOrigins := strings.Trim(os.Getenv("OLLAMA_ORIGINS"), "\"'"); allowedOrigins != "" {
		config.AllowOrigins = strings.Split(allowedOrigins, ",")
	}

Michael Yang's avatar
Michael Yang committed
1024
1025
1026
1027
1028
1029
1030
1031
	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
1032

Bruce MacDonald's avatar
Bruce MacDonald committed
1033
	r := gin.Default()
1034
1035
	r.Use(
		cors.New(config),
1036
		allowedHostsMiddleware(s.addr),
1037
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
1038

1039
1040
	r.POST("/api/pull", PullModelHandler)
	r.POST("/api/generate", GenerateHandler)
Bruce MacDonald's avatar
Bruce MacDonald committed
1041
	r.POST("/api/chat", ChatHandler)
1042
	r.POST("/api/embeddings", EmbeddingsHandler)
1043
1044
	r.POST("/api/create", CreateModelHandler)
	r.POST("/api/push", PushModelHandler)
Patrick Devine's avatar
Patrick Devine committed
1045
	r.POST("/api/copy", CopyModelHandler)
1046
	r.DELETE("/api/delete", DeleteModelHandler)
Patrick Devine's avatar
Patrick Devine committed
1047
	r.POST("/api/show", ShowModelHandler)
Michael Yang's avatar
Michael Yang committed
1048
	r.POST("/api/blobs/:digest", CreateBlobHandler)
Michael Yang's avatar
Michael Yang committed
1049
	r.HEAD("/api/blobs/:digest", HeadBlobHandler)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1050

1051
1052
1053
	// Compatibility endpoints
	r.POST("/v1/chat/completions", openai.Middleware(), ChatHandler)

Michael Yang's avatar
Michael Yang committed
1054
1055
1056
1057
1058
1059
	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
1060
1061
1062
		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
1063
1064
	}

1065
1066
1067
1068
	return r
}

func Serve(ln net.Listener) error {
Michael Yang's avatar
Michael Yang committed
1069
	level := slog.LevelInfo
1070
	if debug := os.Getenv("OLLAMA_DEBUG"); debug != "" {
Michael Yang's avatar
Michael Yang committed
1071
		level = slog.LevelDebug
1072
	}
Michael Yang's avatar
Michael Yang committed
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088

	handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
		Level:     level,
		AddSource: true,
		ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
			if attr.Key == slog.SourceKey {
				source := attr.Value.Any().(*slog.Source)
				source.File = filepath.Base(source.File)
			}

			return attr
		},
	})

	slog.SetDefault(slog.New(handler))

1089
1090
1091
1092
1093
1094
1095
1096
	blobsDir, err := GetBlobsPath("")
	if err != nil {
		return err
	}
	if err := fixBlobs(blobsDir); err != nil {
		return err
	}

1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
	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
		}
	}

1113
	s := &Server{addr: ln.Addr()}
1114
1115
	r := s.GenerateRoutes()

1116
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1117
	srvr := &http.Server{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1118
1119
1120
		Handler: r,
	}

1121
1122
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
1123
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
1124
1125
	go func() {
		<-signals
1126
1127
		if loaded.runner != nil {
			loaded.runner.Close()
1128
		}
1129
		gpu.Cleanup()
1130
1131
1132
		os.Exit(0)
	}()

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1133
	if err := llm.Init(); err != nil {
1134
1135
1136
		return fmt.Errorf("unable to initialize llm library %w", err)
	}
	if runtime.GOOS == "linux" { // TODO - windows too
1137
		// check compatibility to log warnings
1138
		if _, err := gpu.CheckVRAM(); err != nil {
1139
			slog.Info(err.Error())
1140
1141
1142
		}
	}

1143
	return srvr.Serve(ln)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1144
}
Michael Yang's avatar
Michael Yang committed
1145

1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
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
1171
func streamResponse(c *gin.Context, ch chan any) {
1172
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
1173
1174
1175
1176
1177
1178
1179
1180
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

		bts, err := json.Marshal(val)
		if err != nil {
1181
			slog.Info(fmt.Sprintf("streamResponse: json.Marshal failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1182
1183
1184
			return false
		}

1185
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
1186
1187
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
1188
			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1189
1190
1191
1192
1193
1194
			return false
		}

		return true
	})
}
Bruce MacDonald's avatar
Bruce MacDonald committed
1195

1196
// ChatPrompt builds up a prompt from a series of messages for the currently `loaded` model
1197
func chatPrompt(ctx context.Context, template string, messages []api.Message, numCtx int) (string, error) {
1198
1199
1200
1201
	encode := func(s string) ([]int, error) {
		return loaded.runner.Encode(ctx, s)
	}

1202
	prompt, err := ChatPrompt(template, messages, numCtx, encode)
1203
1204
1205
1206
1207
1208
1209
	if err != nil {
		return "", err
	}

	return prompt, nil
}

Bruce MacDonald's avatar
Bruce MacDonald committed
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
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
	}

1237
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
1238
1239
	if err != nil {
		var pErr *fs.PathError
1240
		if errors.As(err, &pErr) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1241
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
1242
1243
1244
1245
1246
1247
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

1248
	if model.IsEmbedding() {
1249
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "embedding models do not support chat"})
1250
1251
1252
		return
	}

1253
1254
1255
	opts, err := modelOptions(model, req.Options)
	if err != nil {
		if errors.Is(err, api.ErrInvalidOpts) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1256
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
1257
			return
Bruce MacDonald's avatar
Bruce MacDonald committed
1258
		}
1259
1260
1261
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
1262
1263
1264

	var sessionDuration time.Duration
	if req.KeepAlive == nil {
1265
		sessionDuration = getDefaultSessionDuration()
1266
1267
1268
1269
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

Michael Yang's avatar
Michael Yang committed
1270
	if err := load(c, model, &opts, sessionDuration); err != nil {
1271
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
1272
1273
1274
1275
1276
		return
	}

	checkpointLoaded := time.Now()

1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
	// if the first message is not a system message, then add the model's default system message
	if len(req.Messages) > 0 && req.Messages[0].Role != "system" {
		req.Messages = append([]api.Message{
			{
				Role:    "system",
				Content: model.System,
			},
		}, req.Messages...)
	}

	prompt, err := chatPrompt(c.Request.Context(), model.Template, req.Messages, opts.NumCtx)
Bruce MacDonald's avatar
Bruce MacDonald committed
1288
1289
1290
1291
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
1292

1293
	// an empty request loads the model
1294
	if len(req.Messages) == 0 || prompt == "" {
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
		resp := api.ChatResponse{
			CreatedAt: time.Now().UTC(),
			Model:     req.Model,
			Done:      true,
			Message:   api.Message{Role: "assistant"},
		}
		c.JSON(http.StatusOK, resp)
		return
	}

1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
	// only send images that are in the prompt
	var i int
	var images []llm.ImageData
	for _, m := range req.Messages {
		for _, img := range m.Images {
			if !isSupportedImageType(img) {
				c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "unsupported image format"})
				return
			}

			if strings.Contains(prompt, fmt.Sprintf("[img-%d]", i)) {
				images = append(images, llm.ImageData{Data: img, ID: i})
			}
			i += 1
		}
	}

	slog.Debug("chat handler", "prompt", prompt, "images", len(images))
1323

Bruce MacDonald's avatar
Bruce MacDonald committed
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
	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{
1335
				Model:     req.Model,
1336
				CreatedAt: time.Now().UTC(),
1337
				Message:   api.Message{Role: "assistant", Content: r.Content},
Bruce MacDonald's avatar
Bruce MacDonald committed
1338
1339
1340
1341
1342
1343
1344
1345
1346
				Done:      r.Done,
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}

1347
1348
1349
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
Bruce MacDonald's avatar
Bruce MacDonald committed
1350
1351
1352
1353
1354
1355
1356
			}

			ch <- resp
		}

		// Start prediction
		predictReq := llm.PredictOpts{
1357
1358
			Prompt:  prompt,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
1359
			Images:  images,
1360
			Options: opts,
Bruce MacDonald's avatar
Bruce MacDonald committed
1361
1362
1363
1364
1365
1366
1367
		}
		if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
1368
1369
		// Accumulate responses into the final response
		var final api.ChatResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
1370
1371
		var sb strings.Builder
		for resp := range ch {
1372
1373
			switch r := resp.(type) {
			case api.ChatResponse:
1374
				sb.WriteString(r.Message.Content)
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
				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
1387
1388
			}
		}
1389

1390
		final.Message = api.Message{Role: "assistant", Content: sb.String()}
1391
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
1392
1393
1394
1395
1396
		return
	}

	streamResponse(c, ch)
}