routes.go 31.4 KB
Newer Older
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1
2
3
package server

import (
4
	"context"
Michael Yang's avatar
Michael Yang committed
5
	"encoding/json"
6
	"errors"
7
	"fmt"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
8
	"io"
9
	"io/fs"
10
	"log/slog"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
11
12
	"net"
	"net/http"
13
	"os"
14
	"os/signal"
Michael Yang's avatar
Michael Yang committed
15
	"path/filepath"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
16
	"reflect"
17
	"runtime"
Michael Yang's avatar
Michael Yang committed
18
	"strings"
Michael Yang's avatar
Michael Yang committed
19
	"sync"
20
	"syscall"
21
	"time"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
22

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

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

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

37
38
39
40
type Server struct {
	WorkDir string
}

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

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

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

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

65
66
var defaultSessionDuration = 5 * time.Minute

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

214
215
	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
216
217
218
		return
	}

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

	checkpointLoaded := time.Now()

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

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

271
			sb.WriteString(prev)
272
273
		}

274
275
276
		sb.WriteString(p)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	streamResponse(c, ch)
}

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

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

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

434
435
	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
436
437
438
		return
	}

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

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

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

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

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

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

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

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

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

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

504
505
506
	streamResponse(c, ch)
}

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

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

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

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

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

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

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

553
554
555
	streamResponse(c, ch)
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	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
	}

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

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

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

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

	c.JSON(http.StatusOK, resp)
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

907
908
909
910
911
func NewServer() (*Server, error) {
	workDir, err := os.MkdirTemp("", "ollama")
	if err != nil {
		return nil, err
	}
912

913
914
915
916
	return &Server{
		WorkDir: workDir,
	}, nil
}
917

918
919
920
921
func (s *Server) GenerateRoutes() http.Handler {
	var origins []string
	if o := os.Getenv("OLLAMA_ORIGINS"); o != "" {
		origins = strings.Split(o, ",")
922
923
	}

Michael Yang's avatar
Michael Yang committed
924
925
	config := cors.DefaultConfig()
	config.AllowWildcard = true
926
	config.AllowBrowserExtensions = true
Michael Yang's avatar
Michael Yang committed
927

928
	config.AllowOrigins = origins
Michael Yang's avatar
Michael Yang committed
929
930
931
932
933
934
935
936
	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
937

Bruce MacDonald's avatar
Bruce MacDonald committed
938
	r := gin.Default()
939
940
941
	r.Use(
		cors.New(config),
		func(c *gin.Context) {
942
			c.Set("workDir", s.WorkDir)
943
944
945
			c.Next()
		},
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
946

947
948
	r.POST("/api/pull", PullModelHandler)
	r.POST("/api/generate", GenerateHandler)
Bruce MacDonald's avatar
Bruce MacDonald committed
949
	r.POST("/api/chat", ChatHandler)
950
	r.POST("/api/embeddings", EmbeddingsHandler)
951
952
	r.POST("/api/create", CreateModelHandler)
	r.POST("/api/push", PushModelHandler)
Patrick Devine's avatar
Patrick Devine committed
953
	r.POST("/api/copy", CopyModelHandler)
954
	r.DELETE("/api/delete", DeleteModelHandler)
Patrick Devine's avatar
Patrick Devine committed
955
	r.POST("/api/show", ShowModelHandler)
Michael Yang's avatar
Michael Yang committed
956
	r.POST("/api/blobs/:digest", CreateBlobHandler)
Michael Yang's avatar
Michael Yang committed
957
	r.HEAD("/api/blobs/:digest", HeadBlobHandler)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
958

959
960
961
	// Compatibility endpoints
	r.POST("/v1/chat/completions", openai.Middleware(), ChatHandler)

Michael Yang's avatar
Michael Yang committed
962
963
964
965
966
967
	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
968
969
970
		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
971
972
	}

973
974
975
976
	return r
}

func Serve(ln net.Listener) error {
Michael Yang's avatar
Michael Yang committed
977
	level := slog.LevelInfo
978
	if debug := os.Getenv("OLLAMA_DEBUG"); debug != "" {
Michael Yang's avatar
Michael Yang committed
979
		level = slog.LevelDebug
980
	}
Michael Yang's avatar
Michael Yang committed
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996

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

997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
	if noprune := os.Getenv("OLLAMA_NOPRUNE"); noprune == "" {
		// clean up unused layers and manifests
		if err := PruneLayers(); err != nil {
			return err
		}

		manifestsPath, err := GetManifestPath()
		if err != nil {
			return err
		}

		if err := PruneDirectory(manifestsPath); err != nil {
			return err
		}
	}

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

1019
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1020
	srvr := &http.Server{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1021
1022
1023
		Handler: r,
	}

1024
1025
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
1026
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
1027
1028
	go func() {
		<-signals
1029
1030
		if loaded.runner != nil {
			loaded.runner.Close()
1031
		}
1032
		os.RemoveAll(s.WorkDir)
1033
1034
1035
		os.Exit(0)
	}()

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1036
	if err := llm.Init(); err != nil {
1037
1038
1039
		return fmt.Errorf("unable to initialize llm library %w", err)
	}
	if runtime.GOOS == "linux" { // TODO - windows too
1040
		// check compatibility to log warnings
1041
		if _, err := gpu.CheckVRAM(); err != nil {
1042
			slog.Info(err.Error())
1043
1044
1045
		}
	}

1046
	return srvr.Serve(ln)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1047
}
Michael Yang's avatar
Michael Yang committed
1048

1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
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
1074
func streamResponse(c *gin.Context, ch chan any) {
1075
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
1076
1077
1078
1079
1080
1081
1082
1083
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

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

1088
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
1089
1090
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
1091
			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1092
1093
1094
1095
1096
1097
			return false
		}

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

1099
// ChatPrompt builds up a prompt from a series of messages for the currently `loaded` model
1100
func chatPrompt(ctx context.Context, template string, messages []api.Message, numCtx int) (string, error) {
1101
1102
1103
1104
	encode := func(s string) ([]int, error) {
		return loaded.runner.Encode(ctx, s)
	}

1105
	prompt, err := ChatPrompt(template, messages, numCtx, encode)
1106
1107
1108
1109
1110
1111
1112
	if err != nil {
		return "", err
	}

	return prompt, nil
}

Bruce MacDonald's avatar
Bruce MacDonald committed
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
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
	}

1140
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
1141
1142
	if err != nil {
		var pErr *fs.PathError
1143
		if errors.As(err, &pErr) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1144
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
1145
1146
1147
1148
1149
1150
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

1151
	if model.IsEmbedding() {
1152
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "embedding models do not support chat"})
1153
1154
1155
		return
	}

1156
1157
1158
	opts, err := modelOptions(model, req.Options)
	if err != nil {
		if errors.Is(err, api.ErrInvalidOpts) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1159
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
1160
			return
Bruce MacDonald's avatar
Bruce MacDonald committed
1161
		}
1162
1163
1164
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
1165
1166
1167
1168
1169
1170
1171
1172

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

1173
1174
	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
1175
1176
1177
1178
1179
		return
	}

	checkpointLoaded := time.Now()

1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
	// 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
1191
1192
1193
1194
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
1195

1196
	// an empty request loads the model
1197
	if len(req.Messages) == 0 || prompt == "" {
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
		resp := api.ChatResponse{
			CreatedAt: time.Now().UTC(),
			Model:     req.Model,
			Done:      true,
			Message:   api.Message{Role: "assistant"},
		}
		c.JSON(http.StatusOK, resp)
		return
	}

1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
	// 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))
1226

Bruce MacDonald's avatar
Bruce MacDonald committed
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
	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{
1238
				Model:     req.Model,
1239
				CreatedAt: time.Now().UTC(),
1240
				Message:   api.Message{Role: "assistant", Content: r.Content},
Bruce MacDonald's avatar
Bruce MacDonald committed
1241
1242
1243
1244
1245
1246
1247
1248
1249
				Done:      r.Done,
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}

1250
1251
1252
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
Bruce MacDonald's avatar
Bruce MacDonald committed
1253
1254
1255
1256
1257
1258
1259
			}

			ch <- resp
		}

		// Start prediction
		predictReq := llm.PredictOpts{
1260
1261
			Prompt:  prompt,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
1262
			Images:  images,
1263
			Options: opts,
Bruce MacDonald's avatar
Bruce MacDonald committed
1264
1265
1266
1267
1268
1269
1270
		}
		if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
1271
1272
		// Accumulate responses into the final response
		var final api.ChatResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
1273
1274
		var sb strings.Builder
		for resp := range ch {
1275
1276
			switch r := resp.(type) {
			case api.ChatResponse:
1277
				sb.WriteString(r.Message.Content)
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
				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
1290
1291
			}
		}
1292

1293
		final.Message = api.Message{Role: "assistant", Content: sb.String()}
1294
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
1295
1296
1297
1298
1299
		return
	}

	streamResponse(c, ch)
}