"vscode:/vscode.git/clone" did not exist on "092ec713851f94ed65b40f4b6e827deab73c7546"
routes.go 33.4 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
	llama *llm.LlamaServer
Michael Yang's avatar
Michael Yang committed
60
61

	expireTimer *time.Timer
Jeffrey Morgan's avatar
Jeffrey Morgan committed
62

63
64
65
	model      string
	adapters   []string
	projectors []string
66
	*api.Options
Michael Yang's avatar
Michael Yang committed
67
68
}

69
70
var defaultSessionDuration = 5 * time.Minute

Bruce MacDonald's avatar
Bruce MacDonald committed
71
// 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
72
func load(c *gin.Context, model *Model, opts *api.Options, sessionDuration time.Duration) error {
73
74
75
76
77
78
79
80
81
	ctx, cancel := context.WithTimeout(c, 10*time.Second)
	defer cancel()

	needLoad := loaded.llama == nil || // is there a model loaded?
		loaded.model != model.ModelPath || // has the base model changed?
		!reflect.DeepEqual(loaded.adapters, model.AdapterPaths) || // have the adapters changed?
		!reflect.DeepEqual(loaded.projectors, model.ProjectorPaths) || // have the adapters changed?
		!reflect.DeepEqual(loaded.Options.Runner, opts.Runner) || // have the runner options changed?
		loaded.llama.Ping(ctx) != nil
82
83

	if needLoad {
84
		if loaded.llama != nil {
85
			slog.Info("changing loaded model")
86
87
88
89
90
			loaded.llama.Close()
			loaded.llama = nil
			loaded.model = ""
			loaded.adapters = nil
			loaded.projectors = nil
91
			loaded.Options = nil
Michael Yang's avatar
Michael Yang committed
92
		}
Michael Yang's avatar
Michael Yang committed
93

94
		llama, err := llm.NewLlamaServer(model.ModelPath, model.AdapterPaths, model.ProjectorPaths, opts)
Michael Yang's avatar
Michael Yang committed
95
		if err != nil {
96
97
98
			// 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
99
			if errors.Is(llm.ErrUnsupportedFormat, err) || strings.Contains(err.Error(), "failed to load model") {
100
101
102
				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)
			}

103
			return err
Michael Yang's avatar
Michael Yang committed
104
105
		}

106
107
108
109
		loaded.model = model.ModelPath
		loaded.adapters = model.AdapterPaths
		loaded.projectors = model.ProjectorPaths
		loaded.llama = llama
Michael Yang's avatar
Michael Yang committed
110
		loaded.Options = opts
Michael Yang's avatar
Michael Yang committed
111
	}
112

Jeffrey Morgan's avatar
Jeffrey Morgan committed
113
114
115
116
	if loaded.expireTimer == nil {
		loaded.expireTimer = time.AfterFunc(sessionDuration, func() {
			loaded.mu.Lock()
			defer loaded.mu.Unlock()
Michael Yang's avatar
Michael Yang committed
117

118
119
			if loaded.llama != nil {
				loaded.llama.Close()
Michael Yang's avatar
Michael Yang committed
120
121
			}

122
123
124
125
			loaded.llama = nil
			loaded.model = ""
			loaded.adapters = nil
			loaded.projectors = nil
126
			loaded.Options = nil
Michael Yang's avatar
Michael Yang committed
127
		})
Michael Yang's avatar
Michael Yang committed
128
	}
129

Jeffrey Morgan's avatar
Jeffrey Morgan committed
130
	loaded.expireTimer.Reset(sessionDuration)
131
132
133
134
135
136
137
138
139
140
141
142
143
144
	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
145
146
}

147
148
149
150
151
152
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
153
154
155
156
157
158
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
159
	err := c.ShouldBindJSON(&req)
Patrick Devine's avatar
Patrick Devine committed
160

Michael Yang's avatar
Michael Yang committed
161
162
163
164
165
166
	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
167
168
169
		return
	}

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

183
184
185
186
187
188
189
	for _, img := range req.Images {
		if !isSupportedImageType(img) {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "unsupported image format"})
			return
		}
	}

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

201
	if model.IsEmbedding() {
202
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "embedding models do not support generate"})
203
204
205
		return
	}

206
207
208
	opts, err := modelOptions(model, req.Options)
	if err != nil {
		if errors.Is(err, api.ErrInvalidOpts) {
Bruce MacDonald's avatar
Bruce MacDonald committed
209
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
210
			return
211
		}
212
213
214
215
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

216
217
	var sessionDuration time.Duration
	if req.KeepAlive == nil {
218
		sessionDuration = getDefaultSessionDuration()
219
220
221
222
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

Michael Yang's avatar
Michael Yang committed
223
	if err := load(c, model, &opts, sessionDuration); err != nil {
224
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
225
226
227
		return
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
228
	// an empty request loads the model
229
230
	// 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
231
	if req.Prompt == "" && req.Template == "" && req.System == "" {
232
		c.JSON(http.StatusOK, api.GenerateResponse{
233
234
			CreatedAt: time.Now().UTC(),
			Model:     req.Model,
Michael Yang's avatar
Michael Yang committed
235
236
			Done:      true,
		})
Bruce MacDonald's avatar
Bruce MacDonald committed
237
238
239
240
241
		return
	}

	checkpointLoaded := time.Now()

Bruce MacDonald's avatar
Bruce MacDonald committed
242
243
244
245
246
	var prompt string
	switch {
	case req.Raw:
		prompt = req.Prompt
	case req.Prompt != "":
247
248
		if req.Template == "" {
			req.Template = model.Template
Bruce MacDonald's avatar
Bruce MacDonald committed
249
250
		}

251
252
253
254
255
256
257
258
259
		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
260
261
262
263
264
265
266
267
268
269
270
271
272
		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
273
		if req.Context != nil {
274
			prev, err := loaded.llama.Detokenize(c.Request.Context(), req.Context)
Bruce MacDonald's avatar
Bruce MacDonald committed
275
276
277
278
279
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}

280
			sb.WriteString(prev)
281
282
		}

283
284
285
		sb.WriteString(p)

		prompt = sb.String()
Bruce MacDonald's avatar
Bruce MacDonald committed
286
287
	}

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

Bruce MacDonald's avatar
Bruce MacDonald committed
290
	ch := make(chan any)
Bruce MacDonald's avatar
Bruce MacDonald committed
291
	var generated strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
292
293
294
	go func() {
		defer close(ch)

295
		fn := func(r llm.CompletionResponse) {
Bruce MacDonald's avatar
Bruce MacDonald committed
296
			// Update model expiration
Bruce MacDonald's avatar
Bruce MacDonald committed
297
298
			loaded.expireTimer.Reset(sessionDuration)

Bruce MacDonald's avatar
Bruce MacDonald committed
299
300
301
302
			// 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
303
304
			}

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

318
319
320
321
322
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)

				if !req.Raw {
323
					p, err := Prompt(req.Template, req.System, req.Prompt, generated.String(), false)
324
					if err != nil {
325
						c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
326
327
						return
					}
328
329

					// TODO (jmorganca): encode() should not strip special tokens
330
					tokens, err := loaded.llama.Tokenize(c.Request.Context(), p)
331
332
333
334
					if err != nil {
						ch <- gin.H{"error": err.Error()}
						return
					}
335
336

					resp.Context = append(req.Context, tokens...)
Bruce MacDonald's avatar
Bruce MacDonald committed
337
338
339
340
				}
			}

			ch <- resp
Bruce MacDonald's avatar
Bruce MacDonald committed
341
342
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
343
		var images []llm.ImageData
Michael Yang's avatar
Michael Yang committed
344
		for i := range req.Images {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
345
346
347
348
			images = append(images, llm.ImageData{
				ID:   i,
				Data: req.Images[i],
			})
Michael Yang's avatar
Michael Yang committed
349
350
		}

Bruce MacDonald's avatar
Bruce MacDonald committed
351
		// Start prediction
352
		req := llm.CompletionRequest{
353
354
			Prompt:  prompt,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
355
			Images:  images,
356
			Options: opts,
Bruce MacDonald's avatar
Bruce MacDonald committed
357
		}
358
		if err := loaded.llama.Completion(c.Request.Context(), req, fn); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
359
360
361
362
363
			ch <- gin.H{"error": err.Error()}
		}
	}()

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

		final.Response = sb.String()
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
388
389
390
391
392
393
		return
	}

	streamResponse(c, ch)
}

394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
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
}

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

440
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
441
	if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
442
		var pErr *fs.PathError
443
		if errors.As(err, &pErr) {
Bruce MacDonald's avatar
Bruce MacDonald committed
444
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
445
446
447
448
449
450
451
452
453
			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
454
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
455
			return
Bruce MacDonald's avatar
Bruce MacDonald committed
456
		}
457
458
459
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
460
461
462

	var sessionDuration time.Duration
	if req.KeepAlive == nil {
463
		sessionDuration = getDefaultSessionDuration()
464
465
466
467
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

Michael Yang's avatar
Michael Yang committed
468
	if err := load(c, model, &opts, sessionDuration); err != nil {
469
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
470
471
472
		return
	}

473
474
475
	// an empty request loads the model
	if req.Prompt == "" {
		c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: []float64{}})
Bruce MacDonald's avatar
Bruce MacDonald committed
476
477
478
		return
	}

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

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

492
func PullModelHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
493
	var req api.PullRequest
Michael Yang's avatar
Michael Yang committed
494
495
496
497
498
499
500
	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
501
502
503
		return
	}

Michael Yang's avatar
Michael Yang committed
504
505
506
507
508
509
510
	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"})
511
512
513
		return
	}

514
515
516
	ch := make(chan any)
	go func() {
		defer close(ch)
517
518
		fn := func(r api.ProgressResponse) {
			ch <- r
519
		}
520

Michael Yang's avatar
Michael Yang committed
521
		regOpts := &registryOptions{
522
523
524
			Insecure: req.Insecure,
		}

525
526
527
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
528
		if err := PullModel(ctx, model, regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
529
			ch <- gin.H{"error": err.Error()}
530
531
532
		}
	}()

533
534
535
536
537
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

538
539
540
	streamResponse(c, ch)
}

541
func PushModelHandler(c *gin.Context) {
542
	var req api.PushRequest
Michael Yang's avatar
Michael Yang committed
543
544
545
546
547
548
549
	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
550
551
		return
	}
Michael Yang's avatar
Michael Yang committed
552

Michael Yang's avatar
Michael Yang committed
553
554
555
556
557
558
559
	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"})
560
561
562
		return
	}

563
564
565
	ch := make(chan any)
	go func() {
		defer close(ch)
566
567
		fn := func(r api.ProgressResponse) {
			ch <- r
568
		}
569

Michael Yang's avatar
Michael Yang committed
570
		regOpts := &registryOptions{
571
572
573
			Insecure: req.Insecure,
		}

Michael Yang's avatar
Michael Yang committed
574
575
576
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
577
		if err := PushModel(ctx, model, regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
578
			ch <- gin.H{"error": err.Error()}
579
580
581
		}
	}()

582
583
584
585
586
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

587
588
589
	streamResponse(c, ch)
}

590
func CreateModelHandler(c *gin.Context) {
591
	var req api.CreateRequest
Michael Yang's avatar
Michael Yang committed
592
593
594
595
596
597
598
	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
599
		return
600
601
	}

Michael Yang's avatar
Michael Yang committed
602
603
604
605
606
607
608
	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"})
609
610
611
		return
	}

Michael Yang's avatar
Michael Yang committed
612
	if err := ParseModelPath(model).Validate(); err != nil {
613
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
614
615
616
		return
	}

Michael Yang's avatar
Michael Yang committed
617
618
	if req.Path == "" && req.Modelfile == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
Michael Yang's avatar
Michael Yang committed
619
620
		return
	}
Michael Yang's avatar
Michael Yang committed
621
622
623

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

631
		modelfile = mf
Michael Yang's avatar
Michael Yang committed
632
	}
Michael Yang's avatar
Michael Yang committed
633
634
635
636
637
638
639

	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
640
	ch := make(chan any)
Michael Yang's avatar
Michael Yang committed
641
642
	go func() {
		defer close(ch)
643
644
		fn := func(resp api.ProgressResponse) {
			ch <- resp
645
646
		}

647
648
649
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
650
		if err := CreateModel(ctx, model, filepath.Dir(req.Path), commands, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
651
			ch <- gin.H{"error": err.Error()}
652
		}
Michael Yang's avatar
Michael Yang committed
653
	}()
Michael Yang's avatar
Michael Yang committed
654

655
656
657
658
659
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

Michael Yang's avatar
Michael Yang committed
660
	streamResponse(c, ch)
Bruce MacDonald's avatar
Bruce MacDonald committed
661
662
}

663
664
func DeleteModelHandler(c *gin.Context) {
	var req api.DeleteRequest
Michael Yang's avatar
Michael Yang committed
665
666
667
668
669
670
671
	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()})
672
673
674
		return
	}

Michael Yang's avatar
Michael Yang committed
675
676
677
678
679
680
681
	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"})
682
683
684
		return
	}

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

	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
	}

705
	c.JSON(http.StatusOK, nil)
706
707
}

Patrick Devine's avatar
Patrick Devine committed
708
709
func ShowModelHandler(c *gin.Context) {
	var req api.ShowRequest
Michael Yang's avatar
Michael Yang committed
710
711
712
713
714
715
716
	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
717
718
719
		return
	}

Michael Yang's avatar
Michael Yang committed
720
	if req.Model != "" {
Michael Yang's avatar
Michael Yang committed
721
		// noop
Michael Yang's avatar
Michael Yang committed
722
	} else if req.Name != "" {
Michael Yang's avatar
Michael Yang committed
723
		req.Model = req.Name
Michael Yang's avatar
Michael Yang committed
724
	} else {
725
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
726
727
728
		return
	}

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

	c.JSON(http.StatusOK, resp)
}

742
743
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
	model, err := GetModel(req.Model)
Patrick Devine's avatar
Patrick Devine committed
744
745
746
747
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
748
	modelDetails := api.ModelDetails{
749
		ParentModel:       model.ParentModel,
Patrick Devine's avatar
Patrick Devine committed
750
751
752
753
754
755
756
		Format:            model.Config.ModelFormat,
		Family:            model.Config.ModelFamily,
		Families:          model.Config.ModelFamilies,
		ParameterSize:     model.Config.ModelType,
		QuantizationLevel: model.Config.FileType,
	}

757
758
759
760
761
762
763
764
	if req.System != "" {
		model.System = req.System
	}

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

765
766
767
768
769
	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
770
771
772
773
	resp := &api.ShowResponse{
		License:  strings.Join(model.License, "\n"),
		System:   model.System,
		Template: model.Template,
Patrick Devine's avatar
Patrick Devine committed
774
		Details:  modelDetails,
775
		Messages: msgs,
Patrick Devine's avatar
Patrick Devine committed
776
777
778
779
780
781
782
783
	}

	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
784
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
Patrick Devine's avatar
Patrick Devine committed
785
			}
Patrick Devine's avatar
Patrick Devine committed
786
787
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
Patrick Devine's avatar
Patrick Devine committed
788
789
790
791
		}
	}
	resp.Parameters = strings.Join(params, "\n")

792
793
794
795
796
797
798
799
800
801
802
803
804
	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
805
806
807
	return resp, nil
}

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

Patrick Devine's avatar
Patrick Devine committed
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
	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
831
			Model:   model.ShortName,
Patrick Devine's avatar
Patrick Devine committed
832
833
834
835
836
837
838
			Name:    model.ShortName,
			Size:    model.Size,
			Digest:  model.Digest,
			Details: modelDetails,
		}, nil
	}

Michael Yang's avatar
Michael Yang committed
839
	walkFunc := func(path string, info os.FileInfo, _ error) error {
Patrick Devine's avatar
Patrick Devine committed
840
		if !info.IsDir() {
841
842
843
844
			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), "/")
845

846
			resp, err := modelResponse(canonicalModelPath)
Patrick Devine's avatar
Patrick Devine committed
847
			if err != nil {
848
				slog.Info(fmt.Sprintf("skipping file: %s", canonicalModelPath))
Michael Yang's avatar
Michael Yang committed
849
				// nolint: nilerr
850
				return nil
Patrick Devine's avatar
Patrick Devine committed
851
			}
Michael Yang's avatar
Michael Yang committed
852

Patrick Devine's avatar
Patrick Devine committed
853
854
			resp.ModifiedAt = info.ModTime()
			models = append(models, resp)
Patrick Devine's avatar
Patrick Devine committed
855
		}
Michael Yang's avatar
Michael Yang committed
856

Patrick Devine's avatar
Patrick Devine committed
857
		return nil
Michael Yang's avatar
Michael Yang committed
858
859
	}

860
	if err := filepath.Walk(manifestsPath, walkFunc); err != nil {
Patrick Devine's avatar
Patrick Devine committed
861
862
863
864
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
865
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
866
867
}

Patrick Devine's avatar
Patrick Devine committed
868
869
func CopyModelHandler(c *gin.Context) {
	var req api.CopyRequest
Michael Yang's avatar
Michael Yang committed
870
871
872
873
874
875
876
	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
877
878
879
		return
	}

880
881
882
883
884
	if req.Source == "" || req.Destination == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
		return
	}

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

func CreateBlobHandler(c *gin.Context) {
916
	layer, err := NewLayer(c.Request.Body, "")
Michael Yang's avatar
Michael Yang committed
917
918
919
920
921
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

922
923
	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
924
925
926
		return
	}

927
	if _, err := layer.Commit(); err != nil {
Michael Yang's avatar
Michael Yang committed
928
929
930
931
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
932
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
933
934
}

Michael Yang's avatar
Michael Yang committed
935
936
937
938
939
940
var defaultAllowOrigins = []string{
	"localhost",
	"127.0.0.1",
	"0.0.0.0",
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
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
}

962
func allowedHost(host string) bool {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
963
	if host == "" || host == "localhost" {
964
965
966
967
968
969
970
971
		return true
	}

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

	var tlds = []string{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
972
973
974
		"localhost",
		"local",
		"internal",
975
	}
976

Jeffrey Morgan's avatar
Jeffrey Morgan committed
977
	// check if the host is a local TLD
978
979
980
981
982
983
	for _, tld := range tlds {
		if strings.HasSuffix(host, "."+tld) {
			return true
		}
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
984
	return false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
985
}
986

Jeffrey Morgan's avatar
Jeffrey Morgan committed
987
988
989
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
	return func(c *gin.Context) {
		if addr == nil {
990
991
992
993
			c.Next()
			return
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
994
		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
995
996
997
998
999
1000
1001
1002
1003
			c.Next()
			return
		}

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1004
		if addr, err := netip.ParseAddr(host); err == nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1005
			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1006
1007
1008
1009
1010
				c.Next()
				return
			}
		}

1011
1012
1013
1014
1015
1016
1017
		if allowedHost(host) {
			c.Next()
			return
		}

		c.AbortWithStatus(http.StatusForbidden)
	}
1018
}
1019

1020
func (s *Server) GenerateRoutes() http.Handler {
Michael Yang's avatar
Michael Yang committed
1021
1022
	config := cors.DefaultConfig()
	config.AllowWildcard = true
1023
	config.AllowBrowserExtensions = true
Michael Yang's avatar
Michael Yang committed
1024

1025
1026
1027
1028
	if allowedOrigins := strings.Trim(os.Getenv("OLLAMA_ORIGINS"), "\"'"); allowedOrigins != "" {
		config.AllowOrigins = strings.Split(allowedOrigins, ",")
	}

Michael Yang's avatar
Michael Yang committed
1029
1030
1031
1032
1033
1034
1035
1036
	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
1037

Bruce MacDonald's avatar
Bruce MacDonald committed
1038
	r := gin.Default()
1039
1040
	r.Use(
		cors.New(config),
1041
		allowedHostsMiddleware(s.addr),
1042
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
1043

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

1056
1057
1058
	// Compatibility endpoints
	r.POST("/v1/chat/completions", openai.Middleware(), ChatHandler)

Michael Yang's avatar
Michael Yang committed
1059
1060
1061
1062
1063
1064
	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
1065
1066
1067
		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
1068
1069
	}

1070
1071
1072
1073
	return r
}

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

	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))

1094
1095
1096
1097
1098
1099
1100
1101
	blobsDir, err := GetBlobsPath("")
	if err != nil {
		return err
	}
	if err := fixBlobs(blobsDir); err != nil {
		return err
	}

1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
	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
		}
	}

1118
	s := &Server{addr: ln.Addr()}
1119
1120
	r := s.GenerateRoutes()

1121
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1122
	srvr := &http.Server{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1123
1124
1125
		Handler: r,
	}

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

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

1148
	return srvr.Serve(ln)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1149
}
Michael Yang's avatar
Michael Yang committed
1150

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

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

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

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

1201
// ChatPrompt builds up a prompt from a series of messages for the currently `loaded` model
1202
func chatPrompt(ctx context.Context, template string, messages []api.Message, numCtx int) (string, error) {
1203
	encode := func(s string) ([]int, error) {
1204
		return loaded.llama.Tokenize(ctx, s)
1205
1206
	}

1207
	prompt, err := ChatPrompt(template, messages, numCtx, encode)
1208
1209
1210
1211
1212
1213
1214
	if err != nil {
		return "", err
	}

	return prompt, nil
}

Bruce MacDonald's avatar
Bruce MacDonald committed
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
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
	}

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

1253
	if model.IsEmbedding() {
1254
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "embedding models do not support chat"})
1255
1256
1257
		return
	}

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

	var sessionDuration time.Duration
	if req.KeepAlive == nil {
1270
		sessionDuration = getDefaultSessionDuration()
1271
1272
1273
1274
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

Michael Yang's avatar
Michael Yang committed
1275
	if err := load(c, model, &opts, sessionDuration); err != nil {
1276
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
1277
1278
1279
1280
1281
		return
	}

	checkpointLoaded := time.Now()

1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
	// 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
1293
1294
1295
1296
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
1297

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

1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
	// 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))
1328

Bruce MacDonald's avatar
Bruce MacDonald committed
1329
1330
1331
1332
1333
	ch := make(chan any)

	go func() {
		defer close(ch)

1334
		fn := func(r llm.CompletionResponse) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1335
1336
1337
1338
			// Update model expiration
			loaded.expireTimer.Reset(sessionDuration)

			resp := api.ChatResponse{
1339
				Model:     req.Model,
1340
				CreatedAt: time.Now().UTC(),
1341
				Message:   api.Message{Role: "assistant", Content: r.Content},
Bruce MacDonald's avatar
Bruce MacDonald committed
1342
1343
1344
1345
1346
1347
1348
1349
1350
				Done:      r.Done,
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}

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

			ch <- resp
		}

1359
		if err := loaded.llama.Completion(c.Request.Context(), llm.CompletionRequest{
1360
1361
			Prompt:  prompt,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
1362
			Images:  images,
1363
			Options: opts,
1364
		}, fn); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1365
1366
1367
1368
1369
			ch <- gin.H{"error": err.Error()}
		}
	}()

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

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

	streamResponse(c, ch)
}