routes.go 31 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/auth"
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
39
40
41
type Server struct {
	WorkDir string
}

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 {
Bruce MacDonald's avatar
Bruce MacDonald committed
70
71
	workDir := c.GetString("workDir")

72
73
74
75
76
77
78
	needLoad := loaded.runner == nil || // is there a model loaded?
		loaded.ModelPath != model.ModelPath || // has the base model changed?
		!reflect.DeepEqual(loaded.AdapterPaths, model.AdapterPaths) || // have the adapters changed?
		!reflect.DeepEqual(loaded.Options.Runner, opts.Runner) // have the runner options changed?

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

Michael Yang's avatar
Michael Yang committed
86
		llmRunner, err := llm.New(workDir, model.ModelPath, model.AdapterPaths, model.ProjectorPaths, opts)
Michael Yang's avatar
Michael Yang committed
87
		if err != nil {
88
89
90
			// some older models are not compatible with newer versions of llama.cpp
			// show a generalized compatibility error until there is a better way to
			// check for model compatibility
Bruce MacDonald's avatar
Bruce MacDonald committed
91
			if errors.Is(llm.ErrUnsupportedFormat, err) || strings.Contains(err.Error(), "failed to load model") {
92
93
94
				err = fmt.Errorf("%v: this model may be incompatible with your version of Ollama. If you previously pulled this model, try updating it by running `ollama pull %s`", err, model.ShortName)
			}

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

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

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

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

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

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

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

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

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

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

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

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

Bruce MacDonald's avatar
Bruce MacDonald committed
147
148
149
150
151
152
func GenerateHandler(c *gin.Context) {
	loaded.mu.Lock()
	defer loaded.mu.Unlock()

	checkpointStart := time.Now()
	var req api.GenerateRequest
Michael Yang's avatar
Michael Yang committed
153
	err := c.ShouldBindJSON(&req)
Patrick Devine's avatar
Patrick Devine committed
154

Michael Yang's avatar
Michael Yang committed
155
156
157
158
159
160
	switch {
	case errors.Is(err, io.EOF):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	case err != nil:
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
161
162
163
		return
	}

164
165
166
	// validate the request
	switch {
	case req.Model == "":
167
168
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
169
170
171
	case len(req.Format) > 0 && req.Format != "json":
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
		return
172
173
174
	case req.Raw && (req.Template != "" || req.System != "" || len(req.Context) > 0):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "raw mode does not support template, system, or context"})
		return
175
176
	}

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

184
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
185
	if err != nil {
186
		var pErr *fs.PathError
187
		if errors.As(err, &pErr) {
188
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
189
190
191
192
193
194
195
196
197
			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
198
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
199
			return
200
		}
201
202
203
204
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

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

212
213
	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
214
215
216
		return
	}

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

	checkpointLoaded := time.Now()

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

240
241
242
243
244
245
246
247
248
		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
Bruce MacDonald's avatar
Bruce MacDonald committed
249
		if req.Context != nil {
250
			prev, err := loaded.runner.Decode(c.Request.Context(), req.Context)
Bruce MacDonald's avatar
Bruce MacDonald committed
251
252
253
254
255
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}

256
			sb.WriteString(prev)
257
258
		}

259
260
		// write image tags
		// TODO: limit the number of images to fit in the context similar to the chat endpoint
261
		for i := range req.Images {
262
			req.Prompt += fmt.Sprintf(" [img-%d]", i)
263
264
		}

265
		p, err := Prompt(req.Template, req.System, req.Prompt, "", true)
266
267
268
269
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
270
271
272
273

		sb.WriteString(p)

		prompt = sb.String()
Bruce MacDonald's avatar
Bruce MacDonald committed
274
275
	}

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

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

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

Bruce MacDonald's avatar
Bruce MacDonald committed
288
289
290
291
			// 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
292
293
			}

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

307
308
309
310
311
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)

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

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

					resp.Context = append(req.Context, tokens...)
Bruce MacDonald's avatar
Bruce MacDonald committed
326
327
328
329
				}
			}

			ch <- resp
Bruce MacDonald's avatar
Bruce MacDonald committed
330
331
		}

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

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

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

		final.Response = sb.String()
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
		return
	}

	streamResponse(c, ch)
}

func EmbeddingHandler(c *gin.Context) {
	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
	}

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

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

431
432
	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
433
434
435
		return
	}

436
	if !loaded.Options.EmbeddingOnly {
Bruce MacDonald's avatar
Bruce MacDonald committed
437
438
439
440
		c.JSON(http.StatusBadRequest, gin.H{"error": "embedding option must be set to true"})
		return
	}

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

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

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

Michael Yang's avatar
Michael Yang committed
466
467
468
469
470
471
472
	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"})
473
474
475
		return
	}

476
477
478
	ch := make(chan any)
	go func() {
		defer close(ch)
479
480
		fn := func(r api.ProgressResponse) {
			ch <- r
481
		}
482

483
		regOpts := &auth.RegistryOptions{
484
485
486
			Insecure: req.Insecure,
		}

487
488
489
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

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

495
496
497
498
499
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

500
501
502
	streamResponse(c, ch)
}

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

Michael Yang's avatar
Michael Yang committed
515
516
517
518
519
520
521
	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"})
522
523
524
		return
	}

525
526
527
	ch := make(chan any)
	go func() {
		defer close(ch)
528
529
		fn := func(r api.ProgressResponse) {
			ch <- r
530
		}
531

532
		regOpts := &auth.RegistryOptions{
533
534
535
			Insecure: req.Insecure,
		}

Michael Yang's avatar
Michael Yang committed
536
537
538
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

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

544
545
546
547
548
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

549
550
551
	streamResponse(c, ch)
}

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

Michael Yang's avatar
Michael Yang committed
564
565
566
567
568
569
570
	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"})
571
572
573
		return
	}

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

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

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

593
		modelfile = mf
Michael Yang's avatar
Michael Yang committed
594
	}
Michael Yang's avatar
Michael Yang committed
595
596
597
598
599
600
601

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

609
610
611
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

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

617
618
619
620
621
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

Michael Yang's avatar
Michael Yang committed
622
	streamResponse(c, ch)
Bruce MacDonald's avatar
Bruce MacDonald committed
623
624
}

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

Michael Yang's avatar
Michael Yang committed
637
638
639
640
641
642
643
	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"})
644
645
646
		return
	}

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

	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
	}

667
	c.JSON(http.StatusOK, nil)
668
669
}

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

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

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

	c.JSON(http.StatusOK, resp)
}

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

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

719
720
721
722
723
724
725
726
	if req.System != "" {
		model.System = req.System
	}

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

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

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

754
755
756
757
758
759
760
761
762
763
764
765
766
	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
767
768
769
	return resp, nil
}

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

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

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

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

Patrick Devine's avatar
Patrick Devine committed
815
816
			resp.ModifiedAt = info.ModTime()
			models = append(models, resp)
Patrick Devine's avatar
Patrick Devine committed
817
		}
Michael Yang's avatar
Michael Yang committed
818

Patrick Devine's avatar
Patrick Devine committed
819
		return nil
Michael Yang's avatar
Michael Yang committed
820
821
	}

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

Michael Yang's avatar
Michael Yang committed
827
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
828
829
}

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

842
843
844
845
846
	if req.Source == "" || req.Destination == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
		return
	}

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

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

884
885
	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
886
887
888
		return
	}

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

Michael Yang's avatar
Michael Yang committed
894
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
895
896
}

Michael Yang's avatar
Michael Yang committed
897
898
899
900
901
902
var defaultAllowOrigins = []string{
	"localhost",
	"127.0.0.1",
	"0.0.0.0",
}

903
904
905
906
907
func NewServer() (*Server, error) {
	workDir, err := os.MkdirTemp("", "ollama")
	if err != nil {
		return nil, err
	}
908

909
910
911
912
	return &Server{
		WorkDir: workDir,
	}, nil
}
913

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

Michael Yang's avatar
Michael Yang committed
920
921
	config := cors.DefaultConfig()
	config.AllowWildcard = true
922
	config.AllowBrowserExtensions = true
Michael Yang's avatar
Michael Yang committed
923

924
	config.AllowOrigins = origins
Michael Yang's avatar
Michael Yang committed
925
926
927
928
929
930
931
932
	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
933

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

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

955
956
957
	// Compatibility endpoints
	r.POST("/v1/chat/completions", openai.Middleware(), ChatHandler)

Michael Yang's avatar
Michael Yang committed
958
959
960
961
962
963
	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
964
965
966
		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
967
968
	}

969
970
971
972
	return r
}

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

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

993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
	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()

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

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

1032
1033
1034
1035
	if err := llm.Init(s.WorkDir); err != nil {
		return fmt.Errorf("unable to initialize llm library %w", err)
	}
	if runtime.GOOS == "linux" { // TODO - windows too
1036
		// check compatibility to log warnings
1037
		if _, err := gpu.CheckVRAM(); err != nil {
1038
			slog.Info(err.Error())
1039
1040
1041
		}
	}

1042
	return srvr.Serve(ln)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1043
}
Michael Yang's avatar
Michael Yang committed
1044

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

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

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

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

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

	prompt, err := ChatPrompt(loaded.Model.Template, loaded.Model.System, messages, loaded.Options.NumCtx, encode)
	if err != nil {
		return "", err
	}

	return prompt, nil
}

Bruce MacDonald's avatar
Bruce MacDonald committed
1109
1110
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
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
	}

1136
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
1137
1138
	if err != nil {
		var pErr *fs.PathError
1139
		if errors.As(err, &pErr) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1140
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
1141
1142
1143
1144
1145
1146
1147
1148
1149
			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
1150
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
1151
			return
Bruce MacDonald's avatar
Bruce MacDonald committed
1152
		}
1153
1154
1155
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
1156
1157
1158
1159
1160
1161
1162
1163

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

1164
1165
	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
1166
1167
1168
1169
1170
		return
	}

	checkpointLoaded := time.Now()

1171
	prompt, err := chatPrompt(c.Request.Context(), req.Messages)
Bruce MacDonald's avatar
Bruce MacDonald committed
1172
1173
1174
1175
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
1176

1177
	// an empty request loads the model
1178
	if len(req.Messages) == 0 || prompt == "" {
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
		resp := api.ChatResponse{
			CreatedAt: time.Now().UTC(),
			Model:     req.Model,
			Done:      true,
			Message:   api.Message{Role: "assistant"},
		}
		c.JSON(http.StatusOK, resp)
		return
	}

1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
	// 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))
1207

Bruce MacDonald's avatar
Bruce MacDonald committed
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
	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{
1219
				Model:     req.Model,
1220
				CreatedAt: time.Now().UTC(),
1221
				Message:   api.Message{Role: "assistant", Content: r.Content},
Bruce MacDonald's avatar
Bruce MacDonald committed
1222
1223
1224
1225
1226
1227
1228
1229
1230
				Done:      r.Done,
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}

1231
1232
1233
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
Bruce MacDonald's avatar
Bruce MacDonald committed
1234
1235
1236
1237
1238
1239
1240
			}

			ch <- resp
		}

		// Start prediction
		predictReq := llm.PredictOpts{
1241
1242
			Prompt:  prompt,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
1243
			Images:  images,
1244
			Options: opts,
Bruce MacDonald's avatar
Bruce MacDonald committed
1245
1246
1247
1248
1249
1250
1251
		}
		if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
1252
1253
		// Accumulate responses into the final response
		var final api.ChatResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
1254
1255
		var sb strings.Builder
		for resp := range ch {
1256
1257
			switch r := resp.(type) {
			case api.ChatResponse:
1258
				sb.WriteString(r.Message.Content)
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
				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
1271
1272
			}
		}
1273

1274
		final.Message = api.Message{Role: "assistant", Content: sb.String()}
1275
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
1276
1277
1278
1279
1280
		return
	}

	streamResponse(c, ch)
}