routes.go 33.3 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
25
	"github.com/gin-gonic/gin"

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

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

36
37
38
39
type Server struct {
	WorkDir string
}

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

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

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

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

64
65
var defaultSessionDuration = 5 * time.Minute

Bruce MacDonald's avatar
Bruce MacDonald committed
66
// 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
67
func load(c *gin.Context, model *Model, opts api.Options, sessionDuration time.Duration) error {
Bruce MacDonald's avatar
Bruce MacDonald committed
68
69
	workDir := c.GetString("workDir")

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

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

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

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

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

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

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

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

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

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

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

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

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

	return opts, nil
Bruce MacDonald's avatar
Bruce MacDonald committed
137
138
139
140
141
142
143
144
}

func 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
145
	err := c.ShouldBindJSON(&req)
Patrick Devine's avatar
Patrick Devine committed
146

Michael Yang's avatar
Michael Yang committed
147
148
149
150
151
152
	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
153
154
155
		return
	}

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

169
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
170
	if err != nil {
171
		var pErr *fs.PathError
172
		if errors.As(err, &pErr) {
173
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
174
175
176
177
178
179
180
181
182
			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
183
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
184
			return
185
		}
186
187
188
189
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

190
191
192
193
194
195
196
	var sessionDuration time.Duration
	if req.KeepAlive == nil {
		sessionDuration = defaultSessionDuration
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

197
198
	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
199
200
201
		return
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
202
203
	// an empty request loads the model
	if req.Prompt == "" && req.Template == "" && req.System == "" {
204
		c.JSON(http.StatusOK, api.GenerateResponse{
205
206
			CreatedAt: time.Now().UTC(),
			Model:     req.Model,
Michael Yang's avatar
Michael Yang committed
207
208
			Done:      true,
		})
Bruce MacDonald's avatar
Bruce MacDonald committed
209
210
211
212
213
		return
	}

	checkpointLoaded := time.Now()

Bruce MacDonald's avatar
Bruce MacDonald committed
214
	var prompt string
215
	var promptVars PromptVars
Bruce MacDonald's avatar
Bruce MacDonald committed
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
	switch {
	case req.Raw:
		prompt = req.Prompt
	case req.Prompt != "":
		if req.Template != "" {
			// override the default model template
			model.Template = req.Template
		}

		var rebuild strings.Builder
		if req.Context != nil {
			// TODO: context is deprecated, at some point the context logic within this conditional should be removed
			prevCtx, err := loaded.runner.Decode(c.Request.Context(), req.Context)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}

			// Remove leading spaces from prevCtx if present
			prevCtx = strings.TrimPrefix(prevCtx, " ")
			rebuild.WriteString(prevCtx)
		}
238
		promptVars = PromptVars{
Bruce MacDonald's avatar
Bruce MacDonald committed
239
240
241
			System: req.System,
			Prompt: req.Prompt,
			First:  len(req.Context) == 0,
242
		}
243
244
245
246
247

		if promptVars.System == "" {
			promptVars.System = model.System
		}

248
249
250
251
		for i := range req.Images {
			promptVars.Prompt += fmt.Sprintf(" [img-%d]", i)
		}

252
		p, err := model.PreResponsePrompt(promptVars)
253
254
255
256
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
Bruce MacDonald's avatar
Bruce MacDonald committed
257
258
		rebuild.WriteString(p)
		prompt = rebuild.String()
Bruce MacDonald's avatar
Bruce MacDonald committed
259
260
	}

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

Bruce MacDonald's avatar
Bruce MacDonald committed
263
	ch := make(chan any)
Bruce MacDonald's avatar
Bruce MacDonald committed
264
	var generated strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
265
266
267
	go func() {
		defer close(ch)

Bruce MacDonald's avatar
Bruce MacDonald committed
268
269
		fn := func(r llm.PredictResult) {
			// Update model expiration
Bruce MacDonald's avatar
Bruce MacDonald committed
270
271
272
			loaded.expireAt = time.Now().Add(sessionDuration)
			loaded.expireTimer.Reset(sessionDuration)

Bruce MacDonald's avatar
Bruce MacDonald committed
273
274
275
276
			// 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
277
278
			}

Bruce MacDonald's avatar
Bruce MacDonald committed
279
			resp := api.GenerateResponse{
280
				Model:     req.Model,
281
				CreatedAt: time.Now().UTC(),
282
283
				Done:      r.Done,
				Response:  r.Content,
Bruce MacDonald's avatar
Bruce MacDonald committed
284
285
286
287
288
289
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
Bruce MacDonald's avatar
Bruce MacDonald committed
290
291
			}

292
293
294
295
296
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)

				if !req.Raw {
297
298
299
300
301
302
303
304
					// append the generated text to the history and template it if needed
					promptVars.Response = generated.String()
					result, err := model.PostResponseTemplate(promptVars)
					if err != nil {
						ch <- gin.H{"error": err.Error()}
						return
					}
					embd, err := loaded.runner.Encode(c.Request.Context(), prompt+result)
305
306
307
308
309
					if err != nil {
						ch <- gin.H{"error": err.Error()}
						return
					}
					resp.Context = embd
Bruce MacDonald's avatar
Bruce MacDonald committed
310
311
312
313
				}
			}

			ch <- resp
Bruce MacDonald's avatar
Bruce MacDonald committed
314
315
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
316
		var images []llm.ImageData
Michael Yang's avatar
Michael Yang committed
317
		for i := range req.Images {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
318
319
320
321
			images = append(images, llm.ImageData{
				ID:   i,
				Data: req.Images[i],
			})
Michael Yang's avatar
Michael Yang committed
322
323
		}

Bruce MacDonald's avatar
Bruce MacDonald committed
324
325
		// Start prediction
		predictReq := llm.PredictOpts{
326
327
			Prompt:  prompt,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
328
			Images:  images,
329
			Options: opts,
Bruce MacDonald's avatar
Bruce MacDonald committed
330
331
		}
		if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
332
333
334
335
336
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
337
338
		// Accumulate responses into the final response
		var final api.GenerateResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
339
		var sb strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
340
		for resp := range ch {
341
342
343
344
345
346
347
348
349
350
351
352
353
354
			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
355
356
357
				return
			}
		}
358
359
360

		final.Response = sb.String()
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
		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
	}

387
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
388
	if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
389
		var pErr *fs.PathError
390
		if errors.As(err, &pErr) {
Bruce MacDonald's avatar
Bruce MacDonald committed
391
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
392
393
394
395
396
397
398
399
400
			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
401
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
402
			return
Bruce MacDonald's avatar
Bruce MacDonald committed
403
		}
404
405
406
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
407
408
409
410
411
412
413
414

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

415
416
	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
417
418
419
		return
	}

420
	if !loaded.Options.EmbeddingOnly {
Bruce MacDonald's avatar
Bruce MacDonald committed
421
422
423
424
		c.JSON(http.StatusBadRequest, gin.H{"error": "embedding option must be set to true"})
		return
	}

425
	embedding, err := loaded.runner.Embedding(c.Request.Context(), req.Prompt)
Bruce MacDonald's avatar
Bruce MacDonald committed
426
	if err != nil {
427
		slog.Info(fmt.Sprintf("embedding generation failed: %v", err))
Bruce MacDonald's avatar
Bruce MacDonald committed
428
429
430
431
432
433
434
435
436
437
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
		return
	}

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

438
func PullModelHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
439
	var req api.PullRequest
Michael Yang's avatar
Michael Yang committed
440
441
442
443
444
445
446
	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
447
448
449
		return
	}

Michael Yang's avatar
Michael Yang committed
450
451
452
453
454
455
456
	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"})
457
458
459
		return
	}

460
461
462
	ch := make(chan any)
	go func() {
		defer close(ch)
463
464
		fn := func(r api.ProgressResponse) {
			ch <- r
465
		}
466

467
468
469
470
		regOpts := &RegistryOptions{
			Insecure: req.Insecure,
		}

471
472
473
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
474
		if err := PullModel(ctx, model, regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
475
			ch <- gin.H{"error": err.Error()}
476
477
478
		}
	}()

479
480
481
482
483
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

484
485
486
	streamResponse(c, ch)
}

487
func PushModelHandler(c *gin.Context) {
488
	var req api.PushRequest
Michael Yang's avatar
Michael Yang committed
489
490
491
492
493
494
495
	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
496
497
		return
	}
Michael Yang's avatar
Michael Yang committed
498

Michael Yang's avatar
Michael Yang committed
499
500
501
502
503
504
505
	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"})
506
507
508
		return
	}

509
510
511
	ch := make(chan any)
	go func() {
		defer close(ch)
512
513
		fn := func(r api.ProgressResponse) {
			ch <- r
514
		}
515

516
517
518
519
		regOpts := &RegistryOptions{
			Insecure: req.Insecure,
		}

Michael Yang's avatar
Michael Yang committed
520
521
522
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
523
		if err := PushModel(ctx, model, regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
524
			ch <- gin.H{"error": err.Error()}
525
526
527
		}
	}()

528
529
530
531
532
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

533
534
535
	streamResponse(c, ch)
}

536
func CreateModelHandler(c *gin.Context) {
537
	var req api.CreateRequest
Michael Yang's avatar
Michael Yang committed
538
539
540
541
542
543
544
	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
545
		return
546
547
	}

Michael Yang's avatar
Michael Yang committed
548
549
550
551
552
553
554
	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"})
555
556
557
		return
	}

Michael Yang's avatar
Michael Yang committed
558
	if err := ParseModelPath(model).Validate(); err != nil {
559
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
560
561
562
		return
	}

Michael Yang's avatar
Michael Yang committed
563
564
	if req.Path == "" && req.Modelfile == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
Michael Yang's avatar
Michael Yang committed
565
566
		return
	}
Michael Yang's avatar
Michael Yang committed
567
568
569

	var modelfile io.Reader = strings.NewReader(req.Modelfile)
	if req.Path != "" && req.Modelfile == "" {
570
		mf, err := os.Open(req.Path)
Michael Yang's avatar
Michael Yang committed
571
572
573
574
		if err != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
			return
		}
575
		defer mf.Close()
Michael Yang's avatar
Michael Yang committed
576

577
		modelfile = mf
Michael Yang's avatar
Michael Yang committed
578
	}
Michael Yang's avatar
Michael Yang committed
579
580
581
582
583
584
585

	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
586
	ch := make(chan any)
Michael Yang's avatar
Michael Yang committed
587
588
	go func() {
		defer close(ch)
589
590
		fn := func(resp api.ProgressResponse) {
			ch <- resp
591
592
		}

593
594
595
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
596
		if err := CreateModel(ctx, model, filepath.Dir(req.Path), commands, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
597
			ch <- gin.H{"error": err.Error()}
598
		}
Michael Yang's avatar
Michael Yang committed
599
	}()
Michael Yang's avatar
Michael Yang committed
600

601
602
603
604
605
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

Michael Yang's avatar
Michael Yang committed
606
	streamResponse(c, ch)
Bruce MacDonald's avatar
Bruce MacDonald committed
607
608
}

609
610
func DeleteModelHandler(c *gin.Context) {
	var req api.DeleteRequest
Michael Yang's avatar
Michael Yang committed
611
612
613
614
615
616
617
	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()})
618
619
620
		return
	}

Michael Yang's avatar
Michael Yang committed
621
622
623
624
625
626
627
	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"})
628
629
630
		return
	}

Michael Yang's avatar
Michael Yang committed
631
	if err := DeleteModel(model); err != nil {
632
		if os.IsNotExist(err) {
Michael Yang's avatar
Michael Yang committed
633
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", model)})
634
		} else {
635
636
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
637
638
		return
	}
Michael Yang's avatar
Michael Yang committed
639
640
641
642
643
644
645
646
647
648
649
650

	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
	}

651
	c.JSON(http.StatusOK, nil)
652
653
}

Patrick Devine's avatar
Patrick Devine committed
654
655
func ShowModelHandler(c *gin.Context) {
	var req api.ShowRequest
Michael Yang's avatar
Michael Yang committed
656
657
658
659
660
661
662
	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
663
664
665
		return
	}

Michael Yang's avatar
Michael Yang committed
666
	if req.Model != "" {
Michael Yang's avatar
Michael Yang committed
667
		// noop
Michael Yang's avatar
Michael Yang committed
668
	} else if req.Name != "" {
Michael Yang's avatar
Michael Yang committed
669
		req.Model = req.Name
Michael Yang's avatar
Michael Yang committed
670
	} else {
671
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
672
673
674
		return
	}

675
	resp, err := GetModelInfo(req)
Patrick Devine's avatar
Patrick Devine committed
676
677
	if err != nil {
		if os.IsNotExist(err) {
Michael Yang's avatar
Michael Yang committed
678
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
Patrick Devine's avatar
Patrick Devine committed
679
680
681
682
683
684
685
686
687
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

	c.JSON(http.StatusOK, resp)
}

688
689
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
	model, err := GetModel(req.Model)
Patrick Devine's avatar
Patrick Devine committed
690
691
692
693
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
694
	modelDetails := api.ModelDetails{
695
		ParentModel:       model.ParentModel,
Patrick Devine's avatar
Patrick Devine committed
696
697
698
699
700
701
702
		Format:            model.Config.ModelFormat,
		Family:            model.Config.ModelFamily,
		Families:          model.Config.ModelFamilies,
		ParameterSize:     model.Config.ModelType,
		QuantizationLevel: model.Config.FileType,
	}

703
704
705
706
707
708
709
710
	if req.System != "" {
		model.System = req.System
	}

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

711
712
713
714
715
	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
716
717
718
719
	resp := &api.ShowResponse{
		License:  strings.Join(model.License, "\n"),
		System:   model.System,
		Template: model.Template,
Patrick Devine's avatar
Patrick Devine committed
720
		Details:  modelDetails,
721
		Messages: msgs,
Patrick Devine's avatar
Patrick Devine committed
722
723
724
725
726
727
728
729
	}

	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
730
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
Patrick Devine's avatar
Patrick Devine committed
731
			}
Patrick Devine's avatar
Patrick Devine committed
732
733
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
Patrick Devine's avatar
Patrick Devine committed
734
735
736
737
		}
	}
	resp.Parameters = strings.Join(params, "\n")

738
739
740
741
742
743
744
745
746
747
748
749
750
	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
751
752
753
	return resp, nil
}

754
func ListModelsHandler(c *gin.Context) {
755
	models := make([]api.ModelResponse, 0)
756
	manifestsPath, err := GetManifestPath()
Patrick Devine's avatar
Patrick Devine committed
757
758
759
760
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
761

Patrick Devine's avatar
Patrick Devine committed
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
	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
777
			Model:   model.ShortName,
Patrick Devine's avatar
Patrick Devine committed
778
779
780
781
782
783
784
			Name:    model.ShortName,
			Size:    model.Size,
			Digest:  model.Digest,
			Details: modelDetails,
		}, nil
	}

Michael Yang's avatar
Michael Yang committed
785
	walkFunc := func(path string, info os.FileInfo, _ error) error {
Patrick Devine's avatar
Patrick Devine committed
786
		if !info.IsDir() {
787
788
789
790
			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), "/")
791

792
			resp, err := modelResponse(canonicalModelPath)
Patrick Devine's avatar
Patrick Devine committed
793
			if err != nil {
794
				slog.Info(fmt.Sprintf("skipping file: %s", canonicalModelPath))
Michael Yang's avatar
Michael Yang committed
795
				// nolint: nilerr
796
				return nil
Patrick Devine's avatar
Patrick Devine committed
797
			}
Michael Yang's avatar
Michael Yang committed
798

Patrick Devine's avatar
Patrick Devine committed
799
800
			resp.ModifiedAt = info.ModTime()
			models = append(models, resp)
Patrick Devine's avatar
Patrick Devine committed
801
		}
Michael Yang's avatar
Michael Yang committed
802

Patrick Devine's avatar
Patrick Devine committed
803
		return nil
Michael Yang's avatar
Michael Yang committed
804
805
	}

806
	if err := filepath.Walk(manifestsPath, walkFunc); err != nil {
Patrick Devine's avatar
Patrick Devine committed
807
808
809
810
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
811
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
812
813
}

Patrick Devine's avatar
Patrick Devine committed
814
815
func CopyModelHandler(c *gin.Context) {
	var req api.CopyRequest
Michael Yang's avatar
Michael Yang committed
816
817
818
819
820
821
822
	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
823
824
825
		return
	}

826
827
828
829
830
	if req.Source == "" || req.Destination == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
		return
	}

831
832
833
834
835
	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
836
837
838
839
840
841
842
843
844
845
	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
846
func HeadBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
847
848
849
850
851
852
853
854
855
856
857
	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
858
	c.Status(http.StatusOK)
Michael Yang's avatar
Michael Yang committed
859
860
861
}

func CreateBlobHandler(c *gin.Context) {
862
	layer, err := NewLayer(c.Request.Body, "")
Michael Yang's avatar
Michael Yang committed
863
864
865
866
867
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

868
869
	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
870
871
872
		return
	}

873
	if _, err := layer.Commit(); err != nil {
Michael Yang's avatar
Michael Yang committed
874
875
876
877
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
878
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
879
880
}

Michael Yang's avatar
Michael Yang committed
881
882
883
884
885
886
var defaultAllowOrigins = []string{
	"localhost",
	"127.0.0.1",
	"0.0.0.0",
}

887
888
889
890
891
func NewServer() (*Server, error) {
	workDir, err := os.MkdirTemp("", "ollama")
	if err != nil {
		return nil, err
	}
892

893
894
895
896
	return &Server{
		WorkDir: workDir,
	}, nil
}
897

898
899
900
901
func (s *Server) GenerateRoutes() http.Handler {
	var origins []string
	if o := os.Getenv("OLLAMA_ORIGINS"); o != "" {
		origins = strings.Split(o, ",")
902
903
	}

Michael Yang's avatar
Michael Yang committed
904
905
	config := cors.DefaultConfig()
	config.AllowWildcard = true
906
	config.AllowBrowserExtensions = true
Michael Yang's avatar
Michael Yang committed
907

908
	config.AllowOrigins = origins
Michael Yang's avatar
Michael Yang committed
909
910
911
912
913
914
915
916
	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
917

Bruce MacDonald's avatar
Bruce MacDonald committed
918
	r := gin.Default()
919
920
921
	r.Use(
		cors.New(config),
		func(c *gin.Context) {
922
			c.Set("workDir", s.WorkDir)
923
924
925
			c.Next()
		},
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
926

927
928
	r.POST("/api/pull", PullModelHandler)
	r.POST("/api/generate", GenerateHandler)
Bruce MacDonald's avatar
Bruce MacDonald committed
929
	r.POST("/api/chat", ChatHandler)
Bruce MacDonald's avatar
Bruce MacDonald committed
930
	r.POST("/api/embeddings", EmbeddingHandler)
931
932
	r.POST("/api/create", CreateModelHandler)
	r.POST("/api/push", PushModelHandler)
Patrick Devine's avatar
Patrick Devine committed
933
	r.POST("/api/copy", CopyModelHandler)
934
	r.DELETE("/api/delete", DeleteModelHandler)
Patrick Devine's avatar
Patrick Devine committed
935
	r.POST("/api/show", ShowModelHandler)
Michael Yang's avatar
Michael Yang committed
936
	r.POST("/api/blobs/:digest", CreateBlobHandler)
Michael Yang's avatar
Michael Yang committed
937
	r.HEAD("/api/blobs/:digest", HeadBlobHandler)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
938

939
940
941
	// Compatibility endpoints
	r.POST("/v1/chat/completions", openai.Middleware(), ChatHandler)

Michael Yang's avatar
Michael Yang committed
942
943
944
945
946
947
	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
948
949
950
		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
951
952
	}

953
954
955
956
	return r
}

func Serve(ln net.Listener) error {
Michael Yang's avatar
Michael Yang committed
957
	level := slog.LevelInfo
958
	if debug := os.Getenv("OLLAMA_DEBUG"); debug != "" {
Michael Yang's avatar
Michael Yang committed
959
		level = slog.LevelDebug
960
	}
Michael Yang's avatar
Michael Yang committed
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976

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

977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
	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()

999
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1000
	srvr := &http.Server{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1001
1002
1003
		Handler: r,
	}

1004
1005
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
1006
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
1007
1008
	go func() {
		<-signals
1009
1010
		if loaded.runner != nil {
			loaded.runner.Close()
1011
		}
1012
		os.RemoveAll(s.WorkDir)
1013
1014
1015
		os.Exit(0)
	}()

1016
1017
1018
1019
	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
1020
		// check compatibility to log warnings
1021
		if _, err := gpu.CheckVRAM(); err != nil {
1022
			slog.Info(err.Error())
1023
1024
1025
		}
	}

1026
	return srvr.Serve(ln)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1027
}
Michael Yang's avatar
Michael Yang committed
1028

1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
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
1054
func streamResponse(c *gin.Context, ch chan any) {
1055
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
1056
1057
1058
1059
1060
1061
1062
1063
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

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

1068
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
1069
1070
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
1071
			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1072
1073
1074
1075
1076
1077
			return false
		}

		return true
	})
}
Bruce MacDonald's avatar
Bruce MacDonald committed
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105

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
	}

1106
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
1107
1108
	if err != nil {
		var pErr *fs.PathError
1109
		if errors.As(err, &pErr) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1110
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
1111
1112
1113
1114
1115
1116
1117
1118
1119
			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
1120
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
1121
			return
Bruce MacDonald's avatar
Bruce MacDonald committed
1122
		}
1123
1124
1125
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
1126
1127
1128
1129
1130
1131
1132
1133

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

1134
1135
	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
1136
1137
1138
1139
1140
		return
	}

	// an empty request loads the model
	if len(req.Messages) == 0 {
1141
1142
1143
1144
1145
1146
1147
		resp := api.ChatResponse{
			CreatedAt: time.Now().UTC(),
			Model:     req.Model,
			Done:      true,
			Message:   api.Message{Role: "assistant"},
		}
		c.JSON(http.StatusOK, resp)
Bruce MacDonald's avatar
Bruce MacDonald committed
1148
1149
1150
1151
1152
		return
	}

	checkpointLoaded := time.Now()

1153
	chat, err := model.ChatPrompts(req.Messages)
Bruce MacDonald's avatar
Bruce MacDonald committed
1154
1155
1156
1157
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
1158
1159

	prompt, images, err := trimmedPrompt(c.Request.Context(), chat, model)
1160
1161
1162
1163
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
1164

Michael Yang's avatar
Michael Yang committed
1165
	slog.Debug("chat handler", "prompt", prompt)
1166

Bruce MacDonald's avatar
Bruce MacDonald committed
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
	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{
1178
				Model:     req.Model,
1179
				CreatedAt: time.Now().UTC(),
1180
				Message:   api.Message{Role: "assistant", Content: r.Content},
Bruce MacDonald's avatar
Bruce MacDonald committed
1181
1182
1183
1184
1185
1186
1187
1188
1189
				Done:      r.Done,
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}

1190
1191
1192
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
Bruce MacDonald's avatar
Bruce MacDonald committed
1193
1194
1195
1196
1197
1198
1199
			}

			ch <- resp
		}

		// Start prediction
		predictReq := llm.PredictOpts{
1200
1201
			Prompt:  prompt,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
1202
			Images:  images,
1203
			Options: opts,
Bruce MacDonald's avatar
Bruce MacDonald committed
1204
1205
1206
1207
1208
1209
1210
		}
		if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
1211
1212
		// Accumulate responses into the final response
		var final api.ChatResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
1213
1214
		var sb strings.Builder
		for resp := range ch {
1215
1216
			switch r := resp.(type) {
			case api.ChatResponse:
1217
				sb.WriteString(r.Message.Content)
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
				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
1230
1231
			}
		}
1232

1233
		final.Message = api.Message{Role: "assistant", Content: sb.String()}
1234
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
1235
1236
1237
1238
1239
		return
	}

	streamResponse(c, ch)
}
1240
1241
1242
1243
1244
1245
1246
1247
1248

// promptInfo stores the variables used to template a prompt, and the token length of the resulting template for some model
type promptInfo struct {
	vars     PromptVars
	tokenLen int
}

// trimmedPrompt builds a prompt to send to a running model. It ensures the prompt fits within the max context length,
// while preserving the most recent system message.
Michael Yang's avatar
Michael Yang committed
1249
func trimmedPrompt(ctx context.Context, chat *ChatHistory, model *Model) (string, []llm.ImageData, error) {
1250
	if len(chat.Prompts) == 0 {
Michael Yang's avatar
Michael Yang committed
1251
		return "", nil, nil
1252
1253
1254
1255
1256
1257
	}

	var promptsToAdd []promptInfo
	var totalTokenLength int
	var systemPromptIncluded bool

Michael Yang's avatar
Michael Yang committed
1258
	var images []llm.ImageData
1259
1260
	// reverse iterate through the prompts to build the prompt string in a way that fits the max context length
	for i := len(chat.Prompts) - 1; i >= 0; i-- {
Michael Yang's avatar
Michael Yang committed
1261
1262
		prompt := chat.Prompts[i]
		promptText, err := promptString(model, prompt, i == len(chat.Prompts)-1)
1263
		if err != nil {
Michael Yang's avatar
Michael Yang committed
1264
			return "", nil, err
1265
1266
1267
1268
		}

		encodedTokens, err := loaded.runner.Encode(ctx, promptText)
		if err != nil {
Michael Yang's avatar
Michael Yang committed
1269
			return "", nil, err
1270
1271
1272
1273
1274
1275
		}

		if totalTokenLength+len(encodedTokens) > loaded.NumCtx && i != len(chat.Prompts)-1 {
			break // reached max context length, stop adding more prompts
		}

Michael Yang's avatar
Michael Yang committed
1276
1277
1278
1279
1280
1281
		for j := range prompt.Images {
			if totalTokenLength+768 > loaded.NumCtx {
				// this decreases the token length but overestimating is fine
				prompt.Prompt = strings.ReplaceAll(prompt.Prompt, fmt.Sprintf(" [img-%d]", prompt.Images[j].ID), "")
				continue
			}
Michael Yang's avatar
Michael Yang committed
1282

Michael Yang's avatar
Michael Yang committed
1283
1284
1285
			totalTokenLength += 768
			images = append(images, prompt.Images[j])
		}
1286

1287
		totalTokenLength += len(encodedTokens)
Michael Yang's avatar
Michael Yang committed
1288
1289
		systemPromptIncluded = systemPromptIncluded || prompt.System != ""
		promptsToAdd = append(promptsToAdd, promptInfo{vars: prompt, tokenLen: len(encodedTokens)})
1290
1291
1292
1293
1294
1295
1296
	}

	// ensure the system prompt is included, if not already
	if chat.LastSystem != "" && !systemPromptIncluded {
		var err error
		promptsToAdd, err = includeSystemPrompt(ctx, chat.LastSystem, totalTokenLength, promptsToAdd)
		if err != nil {
Michael Yang's avatar
Michael Yang committed
1297
			return "", nil, err
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
		}
	}

	promptsToAdd[len(promptsToAdd)-1].vars.First = true

	// construct the final prompt string from the prompts which fit within the context window
	var result string
	for i, prompt := range promptsToAdd {
		promptText, err := promptString(model, prompt.vars, i == 0)
		if err != nil {
Michael Yang's avatar
Michael Yang committed
1308
			return "", nil, err
1309
1310
1311
		}
		result = promptText + result
	}
Michael Yang's avatar
Michael Yang committed
1312

Michael Yang's avatar
Michael Yang committed
1313
	return result, images, nil
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
}

// promptString applies the model template to the prompt
func promptString(model *Model, vars PromptVars, isMostRecent bool) (string, error) {
	if isMostRecent {
		p, err := model.PreResponsePrompt(vars)
		if err != nil {
			return "", fmt.Errorf("pre-response template: %w", err)
		}
		return p, nil
	}
	p, err := Prompt(model.Template, vars)
	if err != nil {
		return "", err
	}
	return p, nil
}

// includeSystemPrompt adjusts the prompts to include the system prompt.
func includeSystemPrompt(ctx context.Context, systemPrompt string, totalTokenLength int, promptsToAdd []promptInfo) ([]promptInfo, error) {
	systemTokens, err := loaded.runner.Encode(ctx, systemPrompt)
	if err != nil {
		return nil, err
	}

	for i := len(promptsToAdd) - 1; i >= 0; i-- {
		if totalTokenLength+len(systemTokens) <= loaded.NumCtx {
			promptsToAdd[i].vars.System = systemPrompt
			return promptsToAdd[:i+1], nil
		}
		totalTokenLength -= promptsToAdd[i].tokenLen
	}

	// if got here, system did not fit anywhere, so return the most recent prompt with the system message set
	recent := promptsToAdd[len(promptsToAdd)-1]
	recent.vars.System = systemPrompt
	return []promptInfo{recent}, nil
}