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

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

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

Michael Yang's avatar
Michael Yang committed
36
37
var mode string = gin.DebugMode

38
type Server struct {
39
	addr net.Addr
40
41
}

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

57
	runner llm.LLM
Michael Yang's avatar
Michael Yang committed
58
59
60

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

62
63
	*Model
	*api.Options
Michael Yang's avatar
Michael Yang committed
64
65
}

66
67
var defaultSessionDuration = 5 * time.Minute

Bruce MacDonald's avatar
Bruce MacDonald committed
68
// 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
69
func load(c *gin.Context, model *Model, opts api.Options, sessionDuration time.Duration) error {
70
71
72
73
74
75
76
	needLoad := loaded.runner == nil || // is there a model loaded?
		loaded.ModelPath != model.ModelPath || // has the base model changed?
		!reflect.DeepEqual(loaded.AdapterPaths, model.AdapterPaths) || // have the adapters changed?
		!reflect.DeepEqual(loaded.Options.Runner, opts.Runner) // have the runner options changed?

	if needLoad {
		if loaded.runner != nil {
77
			slog.Info("changing loaded model")
78
79
80
81
			loaded.runner.Close()
			loaded.runner = nil
			loaded.Model = nil
			loaded.Options = nil
Michael Yang's avatar
Michael Yang committed
82
		}
Michael Yang's avatar
Michael Yang committed
83

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

93
			return err
Michael Yang's avatar
Michael Yang committed
94
95
		}

96
97
98
		loaded.Model = model
		loaded.runner = llmRunner
		loaded.Options = &opts
Michael Yang's avatar
Michael Yang committed
99
	}
100

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

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

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

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

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
122
	loaded.expireTimer.Reset(sessionDuration)
123
124
125
126
127
128
129
130
131
132
133
134
135
136
	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
137
138
}

139
140
141
142
143
144
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
145
146
147
148
149
150
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
151
	err := c.ShouldBindJSON(&req)
Patrick Devine's avatar
Patrick Devine committed
152

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

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

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

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

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

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

208
209
210
211
212
213
214
	var sessionDuration time.Duration
	if req.KeepAlive == nil {
		sessionDuration = defaultSessionDuration
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

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

Bruce MacDonald's avatar
Bruce MacDonald committed
220
	// an empty request loads the model
221
222
	// 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
223
	if req.Prompt == "" && req.Template == "" && req.System == "" {
224
		c.JSON(http.StatusOK, api.GenerateResponse{
225
226
			CreatedAt: time.Now().UTC(),
			Model:     req.Model,
Michael Yang's avatar
Michael Yang committed
227
228
			Done:      true,
		})
Bruce MacDonald's avatar
Bruce MacDonald committed
229
230
231
232
233
		return
	}

	checkpointLoaded := time.Now()

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

243
244
245
246
247
248
249
250
251
		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
252
253
254
255
256
257
258
259
260
261
262
263
264
		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
265
		if req.Context != nil {
266
			prev, err := loaded.runner.Decode(c.Request.Context(), req.Context)
Bruce MacDonald's avatar
Bruce MacDonald committed
267
268
269
270
271
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}

272
			sb.WriteString(prev)
273
274
		}

275
276
277
		sb.WriteString(p)

		prompt = sb.String()
Bruce MacDonald's avatar
Bruce MacDonald committed
278
279
	}

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

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

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

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

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

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

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

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

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

			ch <- resp
Bruce MacDonald's avatar
Bruce MacDonald committed
334
335
		}

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

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

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

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

	streamResponse(c, ch)
}

387
func EmbeddingsHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
	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
	}

407
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
408
	if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
409
		var pErr *fs.PathError
410
		if errors.As(err, &pErr) {
Bruce MacDonald's avatar
Bruce MacDonald committed
411
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
412
413
414
415
416
417
418
419
420
			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
421
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
422
			return
Bruce MacDonald's avatar
Bruce MacDonald committed
423
		}
424
425
426
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
427
428
429
430
431
432
433
434

	var sessionDuration time.Duration
	if req.KeepAlive == nil {
		sessionDuration = defaultSessionDuration
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

435
436
	if err := load(c, model, opts, sessionDuration); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
437
438
439
		return
	}

440
441
442
	// an empty request loads the model
	if req.Prompt == "" {
		c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: []float64{}})
Bruce MacDonald's avatar
Bruce MacDonald committed
443
444
445
		return
	}

446
	embedding, err := loaded.runner.Embedding(c.Request.Context(), req.Prompt)
Bruce MacDonald's avatar
Bruce MacDonald committed
447
	if err != nil {
448
		slog.Info(fmt.Sprintf("embedding generation failed: %v", err))
Bruce MacDonald's avatar
Bruce MacDonald committed
449
450
451
452
453
454
455
456
457
458
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
		return
	}

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

459
func PullModelHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
460
	var req api.PullRequest
Michael Yang's avatar
Michael Yang committed
461
462
463
464
465
466
467
	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
468
469
470
		return
	}

Michael Yang's avatar
Michael Yang committed
471
472
473
474
475
476
477
	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"})
478
479
480
		return
	}

481
482
483
	ch := make(chan any)
	go func() {
		defer close(ch)
484
485
		fn := func(r api.ProgressResponse) {
			ch <- r
486
		}
487

Michael Yang's avatar
Michael Yang committed
488
		regOpts := &registryOptions{
489
490
491
			Insecure: req.Insecure,
		}

492
493
494
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
495
		if err := PullModel(ctx, model, regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
496
			ch <- gin.H{"error": err.Error()}
497
498
499
		}
	}()

500
501
502
503
504
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

505
506
507
	streamResponse(c, ch)
}

508
func PushModelHandler(c *gin.Context) {
509
	var req api.PushRequest
Michael Yang's avatar
Michael Yang committed
510
511
512
513
514
515
516
	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
517
518
		return
	}
Michael Yang's avatar
Michael Yang committed
519

Michael Yang's avatar
Michael Yang committed
520
521
522
523
524
525
526
	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"})
527
528
529
		return
	}

530
531
532
	ch := make(chan any)
	go func() {
		defer close(ch)
533
534
		fn := func(r api.ProgressResponse) {
			ch <- r
535
		}
536

Michael Yang's avatar
Michael Yang committed
537
		regOpts := &registryOptions{
538
539
540
			Insecure: req.Insecure,
		}

Michael Yang's avatar
Michael Yang committed
541
542
543
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
544
		if err := PushModel(ctx, model, regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
545
			ch <- gin.H{"error": err.Error()}
546
547
548
		}
	}()

549
550
551
552
553
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

554
555
556
	streamResponse(c, ch)
}

557
func CreateModelHandler(c *gin.Context) {
558
	var req api.CreateRequest
Michael Yang's avatar
Michael Yang committed
559
560
561
562
563
564
565
	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
566
		return
567
568
	}

Michael Yang's avatar
Michael Yang committed
569
570
571
572
573
574
575
	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"})
576
577
578
		return
	}

Michael Yang's avatar
Michael Yang committed
579
	if err := ParseModelPath(model).Validate(); err != nil {
580
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
581
582
583
		return
	}

Michael Yang's avatar
Michael Yang committed
584
585
	if req.Path == "" && req.Modelfile == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
Michael Yang's avatar
Michael Yang committed
586
587
		return
	}
Michael Yang's avatar
Michael Yang committed
588
589
590

	var modelfile io.Reader = strings.NewReader(req.Modelfile)
	if req.Path != "" && req.Modelfile == "" {
591
		mf, err := os.Open(req.Path)
Michael Yang's avatar
Michael Yang committed
592
593
594
595
		if err != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
			return
		}
596
		defer mf.Close()
Michael Yang's avatar
Michael Yang committed
597

598
		modelfile = mf
Michael Yang's avatar
Michael Yang committed
599
	}
Michael Yang's avatar
Michael Yang committed
600
601
602
603
604
605
606

	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
607
	ch := make(chan any)
Michael Yang's avatar
Michael Yang committed
608
609
	go func() {
		defer close(ch)
610
611
		fn := func(resp api.ProgressResponse) {
			ch <- resp
612
613
		}

614
615
616
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
617
		if err := CreateModel(ctx, model, filepath.Dir(req.Path), commands, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
618
			ch <- gin.H{"error": err.Error()}
619
		}
Michael Yang's avatar
Michael Yang committed
620
	}()
Michael Yang's avatar
Michael Yang committed
621

622
623
624
625
626
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

Michael Yang's avatar
Michael Yang committed
627
	streamResponse(c, ch)
Bruce MacDonald's avatar
Bruce MacDonald committed
628
629
}

630
631
func DeleteModelHandler(c *gin.Context) {
	var req api.DeleteRequest
Michael Yang's avatar
Michael Yang committed
632
633
634
635
636
637
638
	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()})
639
640
641
		return
	}

Michael Yang's avatar
Michael Yang committed
642
643
644
645
646
647
648
	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"})
649
650
651
		return
	}

Michael Yang's avatar
Michael Yang committed
652
	if err := DeleteModel(model); err != nil {
653
		if os.IsNotExist(err) {
Michael Yang's avatar
Michael Yang committed
654
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", model)})
655
		} else {
656
657
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
658
659
		return
	}
Michael Yang's avatar
Michael Yang committed
660
661
662
663
664
665
666
667
668
669
670
671

	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
	}

672
	c.JSON(http.StatusOK, nil)
673
674
}

Patrick Devine's avatar
Patrick Devine committed
675
676
func ShowModelHandler(c *gin.Context) {
	var req api.ShowRequest
Michael Yang's avatar
Michael Yang committed
677
678
679
680
681
682
683
	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
684
685
686
		return
	}

Michael Yang's avatar
Michael Yang committed
687
	if req.Model != "" {
Michael Yang's avatar
Michael Yang committed
688
		// noop
Michael Yang's avatar
Michael Yang committed
689
	} else if req.Name != "" {
Michael Yang's avatar
Michael Yang committed
690
		req.Model = req.Name
Michael Yang's avatar
Michael Yang committed
691
	} else {
692
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
693
694
695
		return
	}

696
	resp, err := GetModelInfo(req)
Patrick Devine's avatar
Patrick Devine committed
697
698
	if err != nil {
		if os.IsNotExist(err) {
Michael Yang's avatar
Michael Yang committed
699
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
Patrick Devine's avatar
Patrick Devine committed
700
701
702
703
704
705
706
707
708
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

	c.JSON(http.StatusOK, resp)
}

709
710
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
	model, err := GetModel(req.Model)
Patrick Devine's avatar
Patrick Devine committed
711
712
713
714
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
715
	modelDetails := api.ModelDetails{
716
		ParentModel:       model.ParentModel,
Patrick Devine's avatar
Patrick Devine committed
717
718
719
720
721
722
723
		Format:            model.Config.ModelFormat,
		Family:            model.Config.ModelFamily,
		Families:          model.Config.ModelFamilies,
		ParameterSize:     model.Config.ModelType,
		QuantizationLevel: model.Config.FileType,
	}

724
725
726
727
728
729
730
731
	if req.System != "" {
		model.System = req.System
	}

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

732
733
734
735
736
	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
737
738
739
740
	resp := &api.ShowResponse{
		License:  strings.Join(model.License, "\n"),
		System:   model.System,
		Template: model.Template,
Patrick Devine's avatar
Patrick Devine committed
741
		Details:  modelDetails,
742
		Messages: msgs,
Patrick Devine's avatar
Patrick Devine committed
743
744
745
746
747
748
749
750
	}

	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
751
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
Patrick Devine's avatar
Patrick Devine committed
752
			}
Patrick Devine's avatar
Patrick Devine committed
753
754
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
Patrick Devine's avatar
Patrick Devine committed
755
756
757
758
		}
	}
	resp.Parameters = strings.Join(params, "\n")

759
760
761
762
763
764
765
766
767
768
769
770
771
	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
772
773
774
	return resp, nil
}

775
func ListModelsHandler(c *gin.Context) {
776
	models := make([]api.ModelResponse, 0)
777
	manifestsPath, err := GetManifestPath()
Patrick Devine's avatar
Patrick Devine committed
778
779
780
781
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
782

Patrick Devine's avatar
Patrick Devine committed
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
	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
798
			Model:   model.ShortName,
Patrick Devine's avatar
Patrick Devine committed
799
800
801
802
803
804
805
			Name:    model.ShortName,
			Size:    model.Size,
			Digest:  model.Digest,
			Details: modelDetails,
		}, nil
	}

Michael Yang's avatar
Michael Yang committed
806
	walkFunc := func(path string, info os.FileInfo, _ error) error {
Patrick Devine's avatar
Patrick Devine committed
807
		if !info.IsDir() {
808
809
810
811
			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), "/")
812

813
			resp, err := modelResponse(canonicalModelPath)
Patrick Devine's avatar
Patrick Devine committed
814
			if err != nil {
815
				slog.Info(fmt.Sprintf("skipping file: %s", canonicalModelPath))
Michael Yang's avatar
Michael Yang committed
816
				// nolint: nilerr
817
				return nil
Patrick Devine's avatar
Patrick Devine committed
818
			}
Michael Yang's avatar
Michael Yang committed
819

Patrick Devine's avatar
Patrick Devine committed
820
821
			resp.ModifiedAt = info.ModTime()
			models = append(models, resp)
Patrick Devine's avatar
Patrick Devine committed
822
		}
Michael Yang's avatar
Michael Yang committed
823

Patrick Devine's avatar
Patrick Devine committed
824
		return nil
Michael Yang's avatar
Michael Yang committed
825
826
	}

827
	if err := filepath.Walk(manifestsPath, walkFunc); err != nil {
Patrick Devine's avatar
Patrick Devine committed
828
829
830
831
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
832
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
833
834
}

Patrick Devine's avatar
Patrick Devine committed
835
836
func CopyModelHandler(c *gin.Context) {
	var req api.CopyRequest
Michael Yang's avatar
Michael Yang committed
837
838
839
840
841
842
843
	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
844
845
846
		return
	}

847
848
849
850
851
	if req.Source == "" || req.Destination == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
		return
	}

852
853
854
855
856
	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
857
858
859
860
861
862
863
864
865
866
	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
867
func HeadBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
868
869
870
871
872
873
874
875
876
877
878
	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
879
	c.Status(http.StatusOK)
Michael Yang's avatar
Michael Yang committed
880
881
882
}

func CreateBlobHandler(c *gin.Context) {
883
	layer, err := NewLayer(c.Request.Body, "")
Michael Yang's avatar
Michael Yang committed
884
885
886
887
888
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

889
890
	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
891
892
893
		return
	}

894
	if _, err := layer.Commit(); err != nil {
Michael Yang's avatar
Michael Yang committed
895
896
897
898
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
899
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
900
901
}

Michael Yang's avatar
Michael Yang committed
902
903
904
905
906
907
var defaultAllowOrigins = []string{
	"localhost",
	"127.0.0.1",
	"0.0.0.0",
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
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
}

929
func allowedHost(host string) bool {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
930
	if host == "" || host == "localhost" {
931
932
933
934
935
936
937
938
		return true
	}

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

	var tlds = []string{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
939
940
941
		"localhost",
		"local",
		"internal",
942
	}
943

Jeffrey Morgan's avatar
Jeffrey Morgan committed
944
	// check if the host is a local TLD
945
946
947
948
949
950
	for _, tld := range tlds {
		if strings.HasSuffix(host, "."+tld) {
			return true
		}
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
951
	return false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
952
}
953

Jeffrey Morgan's avatar
Jeffrey Morgan committed
954
955
956
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
	return func(c *gin.Context) {
		if addr == nil {
957
958
959
960
			c.Next()
			return
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
961
		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
962
963
964
965
966
967
968
969
970
			c.Next()
			return
		}

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
971
		if addr, err := netip.ParseAddr(host); err == nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
972
			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
973
974
975
976
977
				c.Next()
				return
			}
		}

978
979
980
981
982
983
984
		if allowedHost(host) {
			c.Next()
			return
		}

		c.AbortWithStatus(http.StatusForbidden)
	}
985
}
986

987
988
989
990
func (s *Server) GenerateRoutes() http.Handler {
	var origins []string
	if o := os.Getenv("OLLAMA_ORIGINS"); o != "" {
		origins = strings.Split(o, ",")
991
992
	}

Michael Yang's avatar
Michael Yang committed
993
994
	config := cors.DefaultConfig()
	config.AllowWildcard = true
995
	config.AllowBrowserExtensions = true
Michael Yang's avatar
Michael Yang committed
996

997
	config.AllowOrigins = origins
Michael Yang's avatar
Michael Yang committed
998
999
1000
1001
1002
1003
1004
1005
	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
1006

Bruce MacDonald's avatar
Bruce MacDonald committed
1007
	r := gin.Default()
1008
1009
	r.Use(
		cors.New(config),
1010
		allowedHostsMiddleware(s.addr),
1011
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
1012

1013
1014
	r.POST("/api/pull", PullModelHandler)
	r.POST("/api/generate", GenerateHandler)
Bruce MacDonald's avatar
Bruce MacDonald committed
1015
	r.POST("/api/chat", ChatHandler)
1016
	r.POST("/api/embeddings", EmbeddingsHandler)
1017
1018
	r.POST("/api/create", CreateModelHandler)
	r.POST("/api/push", PushModelHandler)
Patrick Devine's avatar
Patrick Devine committed
1019
	r.POST("/api/copy", CopyModelHandler)
1020
	r.DELETE("/api/delete", DeleteModelHandler)
Patrick Devine's avatar
Patrick Devine committed
1021
	r.POST("/api/show", ShowModelHandler)
Michael Yang's avatar
Michael Yang committed
1022
	r.POST("/api/blobs/:digest", CreateBlobHandler)
Michael Yang's avatar
Michael Yang committed
1023
	r.HEAD("/api/blobs/:digest", HeadBlobHandler)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1024

1025
1026
1027
	// Compatibility endpoints
	r.POST("/v1/chat/completions", openai.Middleware(), ChatHandler)

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

1039
1040
1041
1042
	return r
}

func Serve(ln net.Listener) error {
Michael Yang's avatar
Michael Yang committed
1043
	level := slog.LevelInfo
1044
	if debug := os.Getenv("OLLAMA_DEBUG"); debug != "" {
Michael Yang's avatar
Michael Yang committed
1045
		level = slog.LevelDebug
1046
	}
Michael Yang's avatar
Michael Yang committed
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062

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

1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
	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
		}
	}

1079
	s := &Server{addr: ln.Addr()}
1080
1081
	r := s.GenerateRoutes()

1082
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1083
	srvr := &http.Server{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1084
1085
1086
		Handler: r,
	}

1087
1088
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
1089
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
1090
1091
	go func() {
		<-signals
1092
1093
		if loaded.runner != nil {
			loaded.runner.Close()
1094
		}
1095
		gpu.Cleanup()
1096
1097
1098
		os.Exit(0)
	}()

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1099
	if err := llm.Init(); err != nil {
1100
1101
1102
		return fmt.Errorf("unable to initialize llm library %w", err)
	}
	if runtime.GOOS == "linux" { // TODO - windows too
1103
		// check compatibility to log warnings
1104
		if _, err := gpu.CheckVRAM(); err != nil {
1105
			slog.Info(err.Error())
1106
1107
1108
		}
	}

1109
	return srvr.Serve(ln)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1110
}
Michael Yang's avatar
Michael Yang committed
1111

1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
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
1137
func streamResponse(c *gin.Context, ch chan any) {
1138
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
1139
1140
1141
1142
1143
1144
1145
1146
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

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

1151
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
1152
1153
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
1154
			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1155
1156
1157
1158
1159
1160
			return false
		}

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

1162
// ChatPrompt builds up a prompt from a series of messages for the currently `loaded` model
1163
func chatPrompt(ctx context.Context, template string, messages []api.Message, numCtx int) (string, error) {
1164
1165
1166
1167
	encode := func(s string) ([]int, error) {
		return loaded.runner.Encode(ctx, s)
	}

1168
	prompt, err := ChatPrompt(template, messages, numCtx, encode)
1169
1170
1171
1172
1173
1174
1175
	if err != nil {
		return "", err
	}

	return prompt, nil
}

Bruce MacDonald's avatar
Bruce MacDonald committed
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
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
	}

1203
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
1204
1205
	if err != nil {
		var pErr *fs.PathError
1206
		if errors.As(err, &pErr) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1207
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
1208
1209
1210
1211
1212
1213
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

1214
	if model.IsEmbedding() {
1215
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "embedding models do not support chat"})
1216
1217
1218
		return
	}

1219
1220
1221
	opts, err := modelOptions(model, req.Options)
	if err != nil {
		if errors.Is(err, api.ErrInvalidOpts) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1222
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
1223
			return
Bruce MacDonald's avatar
Bruce MacDonald committed
1224
		}
1225
1226
1227
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
1228
1229
1230
1231
1232
1233
1234
1235

	var sessionDuration time.Duration
	if req.KeepAlive == nil {
		sessionDuration = defaultSessionDuration
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

1236
1237
	if err := load(c, model, opts, sessionDuration); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
1238
1239
1240
1241
1242
		return
	}

	checkpointLoaded := time.Now()

1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
	// 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
1254
1255
1256
1257
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
1258

1259
	// an empty request loads the model
1260
	if len(req.Messages) == 0 || prompt == "" {
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
		resp := api.ChatResponse{
			CreatedAt: time.Now().UTC(),
			Model:     req.Model,
			Done:      true,
			Message:   api.Message{Role: "assistant"},
		}
		c.JSON(http.StatusOK, resp)
		return
	}

1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
	// 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))
1289

Bruce MacDonald's avatar
Bruce MacDonald committed
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
	ch := make(chan any)

	go func() {
		defer close(ch)

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

			resp := api.ChatResponse{
1301
				Model:     req.Model,
1302
				CreatedAt: time.Now().UTC(),
1303
				Message:   api.Message{Role: "assistant", Content: r.Content},
Bruce MacDonald's avatar
Bruce MacDonald committed
1304
1305
1306
1307
1308
1309
1310
1311
1312
				Done:      r.Done,
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}

1313
1314
1315
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
Bruce MacDonald's avatar
Bruce MacDonald committed
1316
1317
1318
1319
1320
1321
1322
			}

			ch <- resp
		}

		// Start prediction
		predictReq := llm.PredictOpts{
1323
1324
			Prompt:  prompt,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
1325
			Images:  images,
1326
			Options: opts,
Bruce MacDonald's avatar
Bruce MacDonald committed
1327
1328
1329
1330
1331
1332
1333
		}
		if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
1334
1335
		// Accumulate responses into the final response
		var final api.ChatResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
1336
1337
		var sb strings.Builder
		for resp := range ch {
1338
1339
			switch r := resp.(type) {
			case api.ChatResponse:
1340
				sb.WriteString(r.Message.Content)
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
				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
1353
1354
			}
		}
1355

1356
		final.Message = api.Message{Role: "assistant", Content: sb.String()}
1357
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
1358
1359
1360
1361
1362
		return
	}

	streamResponse(c, ch)
}