routes.go 33.8 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

71
72
73
74
75
76
77
78
79
80
81
82
func unload() {
	if loaded.llama != nil {
		loaded.llama.Close()
	}

	loaded.llama = nil
	loaded.model = ""
	loaded.adapters = nil
	loaded.projectors = nil
	loaded.Options = nil
}

Bruce MacDonald's avatar
Bruce MacDonald committed
83
// 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
84
func load(c *gin.Context, model *Model, opts api.Options, sessionDuration time.Duration) error {
85
86
87
88
89
90
91
92
93
	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
94
95

	if needLoad {
96
		if loaded.llama != nil {
97
			slog.Info("changing loaded model")
98
			unload()
Michael Yang's avatar
Michael Yang committed
99
		}
Michael Yang's avatar
Michael Yang committed
100

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

110
			return err
Michael Yang's avatar
Michael Yang committed
111
112
		}

113
114
115
116
		loaded.model = model.ModelPath
		loaded.adapters = model.AdapterPaths
		loaded.projectors = model.ProjectorPaths
		loaded.llama = llama
117
		loaded.Options = &opts
118
119
120
121
122
123

		if err = llama.WaitUntilRunning(); err != nil {
			slog.Error("error loading llama server", "error", err)
			unload()
			return err
		}
Michael Yang's avatar
Michael Yang committed
124
	}
125

Jeffrey Morgan's avatar
Jeffrey Morgan committed
126
127
128
129
	if loaded.expireTimer == nil {
		loaded.expireTimer = time.AfterFunc(sessionDuration, func() {
			loaded.mu.Lock()
			defer loaded.mu.Unlock()
130
			unload()
Michael Yang's avatar
Michael Yang committed
131
		})
Michael Yang's avatar
Michael Yang committed
132
	}
133

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

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

Michael Yang's avatar
Michael Yang committed
165
166
167
168
169
170
	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
171
172
173
		return
	}

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

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

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

205
	if model.IsEmbedding() {
206
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "embedding models do not support generate"})
207
208
209
		return
	}

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

220
221
	var sessionDuration time.Duration
	if req.KeepAlive == nil {
222
		sessionDuration = getDefaultSessionDuration()
223
224
225
226
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

227
	if err := load(c, model, opts, sessionDuration); err != nil {
228
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
229
230
231
		return
	}

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

	checkpointLoaded := time.Now()

Bruce MacDonald's avatar
Bruce MacDonald committed
246
247
248
249
250
	var prompt string
	switch {
	case req.Raw:
		prompt = req.Prompt
	case req.Prompt != "":
251
252
		if req.Template == "" {
			req.Template = model.Template
Bruce MacDonald's avatar
Bruce MacDonald committed
253
254
		}

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

284
			sb.WriteString(prev)
285
286
		}

287
288
289
		sb.WriteString(p)

		prompt = sb.String()
Bruce MacDonald's avatar
Bruce MacDonald committed
290
291
	}

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

Bruce MacDonald's avatar
Bruce MacDonald committed
294
	ch := make(chan any)
Bruce MacDonald's avatar
Bruce MacDonald committed
295
	var generated strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
296
297
298
	go func() {
		defer close(ch)

299
		fn := func(r llm.CompletionResponse) {
Bruce MacDonald's avatar
Bruce MacDonald committed
300
			// Update model expiration
Bruce MacDonald's avatar
Bruce MacDonald committed
301
302
			loaded.expireTimer.Reset(sessionDuration)

Bruce MacDonald's avatar
Bruce MacDonald committed
303
304
305
306
			// 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
307
308
			}

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

322
323
324
325
326
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)

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

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

					resp.Context = append(req.Context, tokens...)
Bruce MacDonald's avatar
Bruce MacDonald committed
341
342
343
344
				}
			}

			ch <- resp
Bruce MacDonald's avatar
Bruce MacDonald committed
345
346
		}

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

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

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

		final.Response = sb.String()
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
392
393
394
395
396
397
		return
	}

	streamResponse(c, ch)
}

398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
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
}

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

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

	var sessionDuration time.Duration
	if req.KeepAlive == nil {
467
		sessionDuration = getDefaultSessionDuration()
468
469
470
471
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

472
	if err := load(c, model, opts, sessionDuration); err != nil {
473
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
474
475
476
		return
	}

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

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

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

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

Michael Yang's avatar
Michael Yang committed
508
509
510
511
512
513
514
	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"})
515
516
517
		return
	}

518
519
520
	ch := make(chan any)
	go func() {
		defer close(ch)
521
522
		fn := func(r api.ProgressResponse) {
			ch <- r
523
		}
524

Michael Yang's avatar
Michael Yang committed
525
		regOpts := &registryOptions{
526
527
528
			Insecure: req.Insecure,
		}

529
530
531
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

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

537
538
539
540
541
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

542
543
544
	streamResponse(c, ch)
}

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

Michael Yang's avatar
Michael Yang committed
557
558
559
560
561
562
563
	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"})
564
565
566
		return
	}

567
568
569
	ch := make(chan any)
	go func() {
		defer close(ch)
570
571
		fn := func(r api.ProgressResponse) {
			ch <- r
572
		}
573

Michael Yang's avatar
Michael Yang committed
574
		regOpts := &registryOptions{
575
576
577
			Insecure: req.Insecure,
		}

Michael Yang's avatar
Michael Yang committed
578
579
580
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

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

586
587
588
589
590
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

591
592
593
	streamResponse(c, ch)
}

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

Michael Yang's avatar
Michael Yang committed
606
607
608
609
610
611
612
	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"})
613
614
615
		return
	}

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

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

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

635
		modelfile = mf
Michael Yang's avatar
Michael Yang committed
636
	}
Michael Yang's avatar
Michael Yang committed
637
638
639
640
641
642
643

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

651
652
653
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

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

659
660
661
662
663
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

Michael Yang's avatar
Michael Yang committed
664
	streamResponse(c, ch)
Bruce MacDonald's avatar
Bruce MacDonald committed
665
666
}

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

Michael Yang's avatar
Michael Yang committed
679
680
681
682
683
684
685
	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"})
686
687
688
		return
	}

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

	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
	}

709
	c.JSON(http.StatusOK, nil)
710
711
}

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

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

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

	c.JSON(http.StatusOK, resp)
}

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

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

761
762
763
764
765
766
767
768
	if req.System != "" {
		model.System = req.System
	}

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

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

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

796
797
798
799
800
801
802
803
804
805
806
807
808
	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
809
810
811
	return resp, nil
}

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

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

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

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

Patrick Devine's avatar
Patrick Devine committed
857
858
			resp.ModifiedAt = info.ModTime()
			models = append(models, resp)
Patrick Devine's avatar
Patrick Devine committed
859
		}
Michael Yang's avatar
Michael Yang committed
860

Patrick Devine's avatar
Patrick Devine committed
861
		return nil
Michael Yang's avatar
Michael Yang committed
862
863
	}

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

Michael Yang's avatar
Michael Yang committed
869
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
870
871
}

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

884
885
886
887
888
	if req.Source == "" || req.Destination == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
		return
	}

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

func CreateBlobHandler(c *gin.Context) {
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
	path, err := GetBlobsPath(c.Param("digest"))
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	_, err = os.Stat(path)
	switch {
	case errors.Is(err, os.ErrNotExist):
		// noop
	case err != nil:
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	default:
		c.Status(http.StatusOK)
		return
	}

938
	layer, err := NewLayer(c.Request.Body, "")
Michael Yang's avatar
Michael Yang committed
939
940
941
942
943
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

944
945
	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
946
947
948
		return
	}

949
	if _, err := layer.Commit(); err != nil {
Michael Yang's avatar
Michael Yang committed
950
951
952
953
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
954
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
955
956
}

Michael Yang's avatar
Michael Yang committed
957
958
959
960
961
962
var defaultAllowOrigins = []string{
	"localhost",
	"127.0.0.1",
	"0.0.0.0",
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
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
}

984
func allowedHost(host string) bool {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
985
	if host == "" || host == "localhost" {
986
987
988
989
990
991
992
993
		return true
	}

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

	var tlds = []string{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
994
995
996
		"localhost",
		"local",
		"internal",
997
	}
998

Jeffrey Morgan's avatar
Jeffrey Morgan committed
999
	// check if the host is a local TLD
1000
1001
1002
1003
1004
1005
	for _, tld := range tlds {
		if strings.HasSuffix(host, "."+tld) {
			return true
		}
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1006
	return false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1007
}
1008

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1009
1010
1011
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
	return func(c *gin.Context) {
		if addr == nil {
1012
1013
1014
1015
			c.Next()
			return
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1016
		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
1017
1018
1019
1020
1021
1022
1023
1024
1025
			c.Next()
			return
		}

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1026
		if addr, err := netip.ParseAddr(host); err == nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1027
			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1028
1029
1030
1031
1032
				c.Next()
				return
			}
		}

1033
1034
1035
1036
1037
1038
1039
		if allowedHost(host) {
			c.Next()
			return
		}

		c.AbortWithStatus(http.StatusForbidden)
	}
1040
}
1041

1042
func (s *Server) GenerateRoutes() http.Handler {
Michael Yang's avatar
Michael Yang committed
1043
1044
	config := cors.DefaultConfig()
	config.AllowWildcard = true
1045
	config.AllowBrowserExtensions = true
Michael Yang's avatar
Michael Yang committed
1046

1047
1048
1049
1050
	if allowedOrigins := strings.Trim(os.Getenv("OLLAMA_ORIGINS"), "\"'"); allowedOrigins != "" {
		config.AllowOrigins = strings.Split(allowedOrigins, ",")
	}

Michael Yang's avatar
Michael Yang committed
1051
1052
1053
1054
1055
1056
1057
1058
	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
1059

Bruce MacDonald's avatar
Bruce MacDonald committed
1060
	r := gin.Default()
1061
1062
	r.Use(
		cors.New(config),
1063
		allowedHostsMiddleware(s.addr),
1064
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
1065

1066
1067
	r.POST("/api/pull", PullModelHandler)
	r.POST("/api/generate", GenerateHandler)
Bruce MacDonald's avatar
Bruce MacDonald committed
1068
	r.POST("/api/chat", ChatHandler)
1069
	r.POST("/api/embeddings", EmbeddingsHandler)
1070
1071
	r.POST("/api/create", CreateModelHandler)
	r.POST("/api/push", PushModelHandler)
Patrick Devine's avatar
Patrick Devine committed
1072
	r.POST("/api/copy", CopyModelHandler)
1073
	r.DELETE("/api/delete", DeleteModelHandler)
Patrick Devine's avatar
Patrick Devine committed
1074
	r.POST("/api/show", ShowModelHandler)
Michael Yang's avatar
Michael Yang committed
1075
	r.POST("/api/blobs/:digest", CreateBlobHandler)
Michael Yang's avatar
Michael Yang committed
1076
	r.HEAD("/api/blobs/:digest", HeadBlobHandler)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1077

1078
1079
1080
	// Compatibility endpoints
	r.POST("/v1/chat/completions", openai.Middleware(), ChatHandler)

Michael Yang's avatar
Michael Yang committed
1081
1082
1083
1084
1085
1086
	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
1087
1088
1089
		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
1090
1091
	}

1092
1093
1094
1095
	return r
}

func Serve(ln net.Listener) error {
Michael Yang's avatar
Michael Yang committed
1096
	level := slog.LevelInfo
1097
	if debug := os.Getenv("OLLAMA_DEBUG"); debug != "" {
Michael Yang's avatar
Michael Yang committed
1098
		level = slog.LevelDebug
1099
	}
Michael Yang's avatar
Michael Yang committed
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115

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

1116
1117
1118
1119
1120
1121
1122
1123
	blobsDir, err := GetBlobsPath("")
	if err != nil {
		return err
	}
	if err := fixBlobs(blobsDir); err != nil {
		return err
	}

1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
	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
		}
	}

1140
	s := &Server{addr: ln.Addr()}
1141
1142
	r := s.GenerateRoutes()

1143
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1144
	srvr := &http.Server{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1145
1146
1147
		Handler: r,
	}

1148
1149
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
1150
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
1151
1152
	go func() {
		<-signals
1153
		unload()
1154
		gpu.Cleanup()
1155
1156
1157
		os.Exit(0)
	}()

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1158
	if err := llm.Init(); err != nil {
1159
1160
1161
		return fmt.Errorf("unable to initialize llm library %w", err)
	}
	if runtime.GOOS == "linux" { // TODO - windows too
1162
		// check compatibility to log warnings
1163
		if _, err := gpu.CheckVRAM(); err != nil {
1164
			slog.Info(err.Error())
1165
1166
1167
		}
	}

1168
	return srvr.Serve(ln)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1169
}
Michael Yang's avatar
Michael Yang committed
1170

1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
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
1196
func streamResponse(c *gin.Context, ch chan any) {
1197
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
1198
1199
1200
1201
1202
1203
1204
1205
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

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

1210
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
1211
1212
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
1213
			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1214
1215
1216
1217
1218
1219
			return false
		}

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

1221
// ChatPrompt builds up a prompt from a series of messages for the currently `loaded` model
1222
func chatPrompt(ctx context.Context, template string, messages []api.Message, numCtx int) (string, error) {
1223
	encode := func(s string) ([]int, error) {
1224
		return loaded.llama.Tokenize(ctx, s)
1225
1226
	}

1227
	prompt, err := ChatPrompt(template, messages, numCtx, encode)
1228
1229
1230
1231
1232
1233
1234
	if err != nil {
		return "", err
	}

	return prompt, nil
}

Bruce MacDonald's avatar
Bruce MacDonald committed
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
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
	}

1262
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
1263
1264
	if err != nil {
		var pErr *fs.PathError
1265
		if errors.As(err, &pErr) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1266
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
1267
1268
1269
1270
1271
1272
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

1273
	if model.IsEmbedding() {
1274
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "embedding models do not support chat"})
1275
1276
1277
		return
	}

1278
1279
1280
	opts, err := modelOptions(model, req.Options)
	if err != nil {
		if errors.Is(err, api.ErrInvalidOpts) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1281
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
1282
			return
Bruce MacDonald's avatar
Bruce MacDonald committed
1283
		}
1284
1285
1286
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
1287
1288
1289

	var sessionDuration time.Duration
	if req.KeepAlive == nil {
1290
		sessionDuration = getDefaultSessionDuration()
1291
1292
1293
1294
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

1295
	if err := load(c, model, opts, sessionDuration); err != nil {
1296
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
1297
1298
1299
1300
1301
		return
	}

	checkpointLoaded := time.Now()

1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
	// 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
1313
1314
1315
1316
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
1317

1318
	// an empty request loads the model
1319
	if len(req.Messages) == 0 || prompt == "" {
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
		resp := api.ChatResponse{
			CreatedAt: time.Now().UTC(),
			Model:     req.Model,
			Done:      true,
			Message:   api.Message{Role: "assistant"},
		}
		c.JSON(http.StatusOK, resp)
		return
	}

1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
	// 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))
1348

Bruce MacDonald's avatar
Bruce MacDonald committed
1349
1350
1351
1352
1353
	ch := make(chan any)

	go func() {
		defer close(ch)

1354
		fn := func(r llm.CompletionResponse) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1355
1356
1357
1358
			// Update model expiration
			loaded.expireTimer.Reset(sessionDuration)

			resp := api.ChatResponse{
1359
				Model:     req.Model,
1360
				CreatedAt: time.Now().UTC(),
1361
				Message:   api.Message{Role: "assistant", Content: r.Content},
Bruce MacDonald's avatar
Bruce MacDonald committed
1362
1363
1364
1365
1366
1367
1368
1369
1370
				Done:      r.Done,
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}

1371
1372
1373
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
Bruce MacDonald's avatar
Bruce MacDonald committed
1374
1375
1376
1377
1378
			}

			ch <- resp
		}

1379
		if err := loaded.llama.Completion(c.Request.Context(), llm.CompletionRequest{
1380
1381
			Prompt:  prompt,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
1382
			Images:  images,
1383
			Options: opts,
1384
		}, fn); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1385
1386
1387
1388
1389
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
1390
1391
		// Accumulate responses into the final response
		var final api.ChatResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
1392
1393
		var sb strings.Builder
		for resp := range ch {
1394
1395
			switch r := resp.(type) {
			case api.ChatResponse:
1396
				sb.WriteString(r.Message.Content)
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
				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
1409
1410
			}
		}
1411

1412
		final.Message = api.Message{Role: "assistant", Content: sb.String()}
1413
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
1414
1415
1416
1417
1418
		return
	}

	streamResponse(c, ch)
}