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

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

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

28
29
30
31
	"github.com/ollama/ollama/api"
	"github.com/ollama/ollama/gpu"
	"github.com/ollama/ollama/llm"
	"github.com/ollama/ollama/openai"
32
	"github.com/ollama/ollama/parser"
33
	"github.com/ollama/ollama/server/envconfig"
34
	"github.com/ollama/ollama/types/errtypes"
Michael Yang's avatar
Michael Yang committed
35
	"github.com/ollama/ollama/types/model"
36
	"github.com/ollama/ollama/version"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
37
38
)

Michael Yang's avatar
Michael Yang committed
39
40
var mode string = gin.DebugMode

41
type Server struct {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
42
43
	addr  net.Addr
	sched *Scheduler
44
45
}

Michael Yang's avatar
Michael Yang committed
46
47
48
49
50
51
52
53
54
55
56
57
func init() {
	switch mode {
	case gin.DebugMode:
	case gin.ReleaseMode:
	case gin.TestMode:
	default:
		mode = gin.DebugMode
	}

	gin.SetMode(mode)
}

58
59
var defaultSessionDuration = 5 * time.Minute

60
61
62
63
64
65
66
67
68
69
70
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
71
72
}

73
74
75
76
77
78
func isSupportedImageType(image []byte) bool {
	contentType := http.DetectContentType(image)
	allowedTypes := []string{"image/jpeg", "image/jpg", "image/png"}
	return slices.Contains(allowedTypes, contentType)
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
79
func (s *Server) GenerateHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
80
81
82

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

Michael Yang's avatar
Michael Yang committed
85
86
87
88
89
90
	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
91
92
93
		return
	}

94
95
96
	// validate the request
	switch {
	case req.Model == "":
97
98
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
99
100
101
	case len(req.Format) > 0 && req.Format != "json":
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
		return
102
103
104
	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
105
106
	}

107
108
109
110
111
112
113
	for _, img := range req.Images {
		if !isSupportedImageType(img) {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "unsupported image format"})
			return
		}
	}

114
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
115
	if err != nil {
116
		var pErr *fs.PathError
117
		if errors.As(err, &pErr) {
118
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
119
120
121
122
123
124
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

125
	if model.IsEmbedding() {
126
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "embedding models do not support generate"})
127
128
129
		return
	}

130
131
132
133
134
135
	opts, err := modelOptions(model, req.Options)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

136
137
	var sessionDuration time.Duration
	if req.KeepAlive == nil {
138
		sessionDuration = getDefaultSessionDuration()
139
140
141
142
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
143
144
145
146
147
	rCh, eCh := s.sched.GetRunner(c.Request.Context(), model, opts, sessionDuration)
	var runner *runnerRef
	select {
	case runner = <-rCh:
	case err = <-eCh:
148
		handleErrorResponse(c, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
149
150
151
		return
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
152
	// an empty request loads the model
153
154
	// 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
155
	if req.Prompt == "" && req.Template == "" && req.System == "" {
156
		c.JSON(http.StatusOK, api.GenerateResponse{
157
158
159
160
			CreatedAt:  time.Now().UTC(),
			Model:      req.Model,
			Done:       true,
			DoneReason: "load",
Michael Yang's avatar
Michael Yang committed
161
		})
Bruce MacDonald's avatar
Bruce MacDonald committed
162
163
164
165
166
		return
	}

	checkpointLoaded := time.Now()

Bruce MacDonald's avatar
Bruce MacDonald committed
167
168
169
170
171
	var prompt string
	switch {
	case req.Raw:
		prompt = req.Prompt
	case req.Prompt != "":
172
173
		if req.Template == "" {
			req.Template = model.Template
Bruce MacDonald's avatar
Bruce MacDonald committed
174
175
		}

176
177
178
179
180
181
182
183
184
		if req.System == "" {
			req.System = model.System
		}

		slog.Debug("generate handler", "prompt", req.Prompt)
		slog.Debug("generate handler", "template", req.Template)
		slog.Debug("generate handler", "system", req.System)

		var sb strings.Builder
Michael Yang's avatar
Michael Yang committed
185
186
187
188
189
190
191
192
193
194
195
196
197
		for i := range req.Images {
			fmt.Fprintf(&sb, "[img-%d] ", i)
		}

		sb.WriteString(req.Prompt)

		p, err := Prompt(req.Template, req.System, sb.String(), "", true)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		sb.Reset()
Bruce MacDonald's avatar
Bruce MacDonald committed
198
		if req.Context != nil {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
199
			prev, err := runner.llama.Detokenize(c.Request.Context(), req.Context)
Bruce MacDonald's avatar
Bruce MacDonald committed
200
201
202
203
204
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}

205
			sb.WriteString(prev)
206
207
		}

208
209
210
		sb.WriteString(p)

		prompt = sb.String()
Bruce MacDonald's avatar
Bruce MacDonald committed
211
212
	}

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

Bruce MacDonald's avatar
Bruce MacDonald committed
215
	ch := make(chan any)
Bruce MacDonald's avatar
Bruce MacDonald committed
216
	var generated strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
217
218
219
	go func() {
		defer close(ch)

220
		fn := func(r llm.CompletionResponse) {
Bruce MacDonald's avatar
Bruce MacDonald committed
221
222
223
224
			// 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
225
226
			}

Bruce MacDonald's avatar
Bruce MacDonald committed
227
			resp := api.GenerateResponse{
228
229
230
231
232
				Model:      req.Model,
				CreatedAt:  time.Now().UTC(),
				Done:       r.Done,
				Response:   r.Content,
				DoneReason: r.DoneReason,
Bruce MacDonald's avatar
Bruce MacDonald committed
233
234
235
236
237
238
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
Bruce MacDonald's avatar
Bruce MacDonald committed
239
240
			}

241
242
243
244
245
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)

				if !req.Raw {
246
					p, err := Prompt(req.Template, req.System, req.Prompt, generated.String(), false)
247
					if err != nil {
248
						c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
249
250
						return
					}
251
252

					// TODO (jmorganca): encode() should not strip special tokens
Daniel Hiltgen's avatar
Daniel Hiltgen committed
253
					tokens, err := runner.llama.Tokenize(c.Request.Context(), p)
254
255
256
257
					if err != nil {
						ch <- gin.H{"error": err.Error()}
						return
					}
258
259

					resp.Context = append(req.Context, tokens...)
Bruce MacDonald's avatar
Bruce MacDonald committed
260
261
262
263
				}
			}

			ch <- resp
Bruce MacDonald's avatar
Bruce MacDonald committed
264
265
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
266
		var images []llm.ImageData
Michael Yang's avatar
Michael Yang committed
267
		for i := range req.Images {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
268
269
270
271
			images = append(images, llm.ImageData{
				ID:   i,
				Data: req.Images[i],
			})
Michael Yang's avatar
Michael Yang committed
272
273
		}

Bruce MacDonald's avatar
Bruce MacDonald committed
274
		// Start prediction
275
		req := llm.CompletionRequest{
276
277
			Prompt:  prompt,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
278
			Images:  images,
279
			Options: opts,
Bruce MacDonald's avatar
Bruce MacDonald committed
280
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
281
		if err := runner.llama.Completion(c.Request.Context(), req, fn); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
282
283
284
285
286
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
287
288
		// Accumulate responses into the final response
		var final api.GenerateResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
289
		var sb strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
290
		for resp := range ch {
291
292
293
294
295
296
297
298
299
300
301
302
303
304
			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
305
306
307
				return
			}
		}
308
309
310

		final.Response = sb.String()
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
311
312
313
314
315
316
		return
	}

	streamResponse(c, ch)
}

317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
func getDefaultSessionDuration() time.Duration {
	if t, exists := os.LookupEnv("OLLAMA_KEEP_ALIVE"); exists {
		v, err := strconv.Atoi(t)
		if err != nil {
			d, err := time.ParseDuration(t)
			if err != nil {
				return defaultSessionDuration
			}

			if d < 0 {
				return time.Duration(math.MaxInt64)
			}

			return d
		}

		d := time.Duration(v) * time.Second
		if d < 0 {
			return time.Duration(math.MaxInt64)
		}
		return d
	}

	return defaultSessionDuration
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
343
func (s *Server) EmbeddingsHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
	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
	}

360
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
361
	if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
362
		var pErr *fs.PathError
363
		if errors.As(err, &pErr) {
Bruce MacDonald's avatar
Bruce MacDonald committed
364
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
365
366
367
368
369
370
371
372
373
374
375
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	opts, err := modelOptions(model, req.Options)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
376
377
378

	var sessionDuration time.Duration
	if req.KeepAlive == nil {
379
		sessionDuration = getDefaultSessionDuration()
380
381
382
383
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
384
385
386
387
388
	rCh, eCh := s.sched.GetRunner(c.Request.Context(), model, opts, sessionDuration)
	var runner *runnerRef
	select {
	case runner = <-rCh:
	case err = <-eCh:
389
		handleErrorResponse(c, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
390
391
392
		return
	}

393
394
395
	// an empty request loads the model
	if req.Prompt == "" {
		c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: []float64{}})
Bruce MacDonald's avatar
Bruce MacDonald committed
396
397
398
		return
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
399
	embedding, err := runner.llama.Embedding(c.Request.Context(), req.Prompt)
Bruce MacDonald's avatar
Bruce MacDonald committed
400
	if err != nil {
401
		slog.Info(fmt.Sprintf("embedding generation failed: %v", err))
Bruce MacDonald's avatar
Bruce MacDonald committed
402
403
404
405
406
407
408
409
410
411
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
		return
	}

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

Daniel Hiltgen's avatar
Daniel Hiltgen committed
412
func (s *Server) PullModelHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
413
	var req api.PullRequest
Michael Yang's avatar
Michael Yang committed
414
415
416
417
418
419
420
	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
421
422
423
		return
	}

Michael Yang's avatar
Michael Yang committed
424
425
426
427
428
429
430
	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"})
431
432
433
		return
	}

434
435
436
	ch := make(chan any)
	go func() {
		defer close(ch)
437
438
		fn := func(r api.ProgressResponse) {
			ch <- r
439
		}
440

Michael Yang's avatar
Michael Yang committed
441
		regOpts := &registryOptions{
442
443
444
			Insecure: req.Insecure,
		}

445
446
447
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
448
		if err := PullModel(ctx, model, regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
449
			ch <- gin.H{"error": err.Error()}
450
451
452
		}
	}()

453
454
455
456
457
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

458
459
460
	streamResponse(c, ch)
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
461
func (s *Server) PushModelHandler(c *gin.Context) {
462
	var req api.PushRequest
Michael Yang's avatar
Michael Yang committed
463
464
465
466
467
468
469
	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
470
471
		return
	}
Michael Yang's avatar
Michael Yang committed
472

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

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

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

Michael Yang's avatar
Michael Yang committed
494
495
496
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

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

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

507
508
509
	streamResponse(c, ch)
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
510
func (s *Server) CreateModelHandler(c *gin.Context) {
511
	var req api.CreateRequest
Michael Yang's avatar
Michael Yang committed
512
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
513
514
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
515
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
516
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
517
		return
518
519
	}

Michael Yang's avatar
Michael Yang committed
520
521
	name := model.ParseName(cmp.Or(req.Model, req.Name))
	if !name.IsValid() {
522
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": errtypes.InvalidModelNameErrMsg})
523
524
525
		return
	}

Michael Yang's avatar
Michael Yang committed
526
527
	if req.Path == "" && req.Modelfile == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
Michael Yang's avatar
Michael Yang committed
528
529
		return
	}
Michael Yang's avatar
Michael Yang committed
530

Michael Yang's avatar
Michael Yang committed
531
	var r io.Reader = strings.NewReader(req.Modelfile)
Michael Yang's avatar
Michael Yang committed
532
	if req.Path != "" && req.Modelfile == "" {
Michael Yang's avatar
Michael Yang committed
533
		f, err := os.Open(req.Path)
Michael Yang's avatar
Michael Yang committed
534
535
536
537
		if err != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
			return
		}
Michael Yang's avatar
Michael Yang committed
538
		defer f.Close()
Michael Yang's avatar
Michael Yang committed
539

Michael Yang's avatar
Michael Yang committed
540
		r = f
Michael Yang's avatar
Michael Yang committed
541
	}
Michael Yang's avatar
Michael Yang committed
542

543
	modelfile, err := parser.ParseFile(r)
Michael Yang's avatar
Michael Yang committed
544
545
546
547
548
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
549
	ch := make(chan any)
Michael Yang's avatar
Michael Yang committed
550
551
	go func() {
		defer close(ch)
552
553
		fn := func(resp api.ProgressResponse) {
			ch <- resp
554
555
		}

556
557
558
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

559
560
561
562
563
564
		quantization := req.Quantization
		if req.Quantize != "" {
			quantization = req.Quantize
		}

		if err := CreateModel(ctx, name.String(), filepath.Dir(req.Path), strings.ToUpper(quantization), modelfile, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
565
			ch <- gin.H{"error": err.Error()}
566
		}
Michael Yang's avatar
Michael Yang committed
567
	}()
Michael Yang's avatar
Michael Yang committed
568

569
570
571
572
573
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

Michael Yang's avatar
Michael Yang committed
574
	streamResponse(c, ch)
Bruce MacDonald's avatar
Bruce MacDonald committed
575
576
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
577
func (s *Server) DeleteModelHandler(c *gin.Context) {
578
	var req api.DeleteRequest
Michael Yang's avatar
Michael Yang committed
579
580
581
582
583
584
585
	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()})
586
587
588
		return
	}

Michael Yang's avatar
Michael Yang committed
589
590
591
592
593
594
595
	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"})
596
597
598
		return
	}

Michael Yang's avatar
Michael Yang committed
599
	if err := DeleteModel(model); err != nil {
600
		if os.IsNotExist(err) {
Michael Yang's avatar
Michael Yang committed
601
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", model)})
602
		} else {
603
604
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
605
606
		return
	}
Michael Yang's avatar
Michael Yang committed
607
608
609
610
611
612
613
614
615
616
617
618

	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
	}

619
	c.JSON(http.StatusOK, nil)
620
621
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
622
func (s *Server) ShowModelHandler(c *gin.Context) {
Patrick Devine's avatar
Patrick Devine committed
623
	var req api.ShowRequest
Michael Yang's avatar
Michael Yang committed
624
625
626
627
628
629
630
	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
631
632
633
		return
	}

Michael Yang's avatar
Michael Yang committed
634
	if req.Model != "" {
Michael Yang's avatar
Michael Yang committed
635
		// noop
Michael Yang's avatar
Michael Yang committed
636
	} else if req.Name != "" {
Michael Yang's avatar
Michael Yang committed
637
		req.Model = req.Name
Michael Yang's avatar
Michael Yang committed
638
	} else {
639
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
640
641
642
		return
	}

643
	resp, err := GetModelInfo(req)
Patrick Devine's avatar
Patrick Devine committed
644
645
	if err != nil {
		if os.IsNotExist(err) {
Michael Yang's avatar
Michael Yang committed
646
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
Patrick Devine's avatar
Patrick Devine committed
647
648
649
650
651
652
653
654
655
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

	c.JSON(http.StatusOK, resp)
}

656
657
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
	model, err := GetModel(req.Model)
Patrick Devine's avatar
Patrick Devine committed
658
659
660
661
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
662
	modelDetails := api.ModelDetails{
663
		ParentModel:       model.ParentModel,
Patrick Devine's avatar
Patrick Devine committed
664
665
666
667
668
669
670
		Format:            model.Config.ModelFormat,
		Family:            model.Config.ModelFamily,
		Families:          model.Config.ModelFamilies,
		ParameterSize:     model.Config.ModelType,
		QuantizationLevel: model.Config.FileType,
	}

671
672
673
674
675
676
677
678
	if req.System != "" {
		model.System = req.System
	}

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

679
680
681
682
683
	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
684
685
686
687
	resp := &api.ShowResponse{
		License:  strings.Join(model.License, "\n"),
		System:   model.System,
		Template: model.Template,
Patrick Devine's avatar
Patrick Devine committed
688
		Details:  modelDetails,
689
		Messages: msgs,
Patrick Devine's avatar
Patrick Devine committed
690
691
692
693
694
695
696
697
	}

	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
698
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
Patrick Devine's avatar
Patrick Devine committed
699
			}
Patrick Devine's avatar
Patrick Devine committed
700
701
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
Patrick Devine's avatar
Patrick Devine committed
702
703
704
705
		}
	}
	resp.Parameters = strings.Join(params, "\n")

706
707
708
709
710
711
	for k, v := range req.Options {
		if _, ok := req.Options[k]; ok {
			model.Options[k] = v
		}
	}

712
	var sb strings.Builder
713
	fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"")
714
715
	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
	fmt.Fprintf(&sb, "# FROM %s\n\n", model.ShortName)
Michael Yang's avatar
Michael Yang committed
716
	fmt.Fprint(&sb, model.String())
717
	resp.Modelfile = sb.String()
718

Patrick Devine's avatar
Patrick Devine committed
719
720
721
	return resp, nil
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
722
func (s *Server) ListModelsHandler(c *gin.Context) {
723
	manifests, err := GetManifestPath()
Patrick Devine's avatar
Patrick Devine committed
724
725
726
727
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
728

729
	models := []api.ModelResponse{}
730
	if err := filepath.Walk(manifests, func(path string, info os.FileInfo, _ error) error {
Patrick Devine's avatar
Patrick Devine committed
731
		if !info.IsDir() {
732
733
734
735
			rel, err := filepath.Rel(manifests, path)
			if err != nil {
				return err
			}
736

737
738
739
740
741
742
			if hidden, err := filepath.Match(".*", filepath.Base(rel)); err != nil {
				return err
			} else if hidden {
				return nil
			}

743
			n := model.ParseNameFromFilepath(rel)
Michael Yang's avatar
Michael Yang committed
744
			if !n.IsValid() {
Michael Yang's avatar
Michael Yang committed
745
				slog.Warn("bad manifest filepath", "path", rel)
Michael Yang's avatar
Michael Yang committed
746
747
748
				return nil
			}

749
			m, err := ParseNamedManifest(n)
Patrick Devine's avatar
Patrick Devine committed
750
			if err != nil {
Michael Yang's avatar
Michael Yang committed
751
752
				slog.Warn("bad manifest", "name", n, "error", err)
				return nil
Patrick Devine's avatar
Patrick Devine committed
753
			}
Michael Yang's avatar
Michael Yang committed
754

755
756
			f, err := m.Config.Open()
			if err != nil {
Michael Yang's avatar
Michael Yang committed
757
758
				slog.Warn("bad manifest config filepath", "name", n, "error", err)
				return nil
759
760
761
762
763
			}
			defer f.Close()

			var c ConfigV2
			if err := json.NewDecoder(f).Decode(&c); err != nil {
Michael Yang's avatar
Michael Yang committed
764
765
				slog.Warn("bad manifest config", "name", n, "error", err)
				return nil
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
			}

			// tag should never be masked
			models = append(models, api.ModelResponse{
				Model:      n.DisplayShortest(),
				Name:       n.DisplayShortest(),
				Size:       m.Size(),
				Digest:     m.Digest,
				ModifiedAt: info.ModTime(),
				Details: api.ModelDetails{
					Format:            c.ModelFormat,
					Family:            c.ModelFamily,
					Families:          c.ModelFamilies,
					ParameterSize:     c.ModelType,
					QuantizationLevel: c.FileType,
				},
			})
Patrick Devine's avatar
Patrick Devine committed
783
		}
Michael Yang's avatar
Michael Yang committed
784

Patrick Devine's avatar
Patrick Devine committed
785
		return nil
786
	}); err != nil {
Patrick Devine's avatar
Patrick Devine committed
787
788
789
790
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

791
792
793
794
795
	slices.SortStableFunc(models, func(i, j api.ModelResponse) int {
		// most recently modified first
		return cmp.Compare(j.ModifiedAt.Unix(), i.ModifiedAt.Unix())
	})

Michael Yang's avatar
Michael Yang committed
796
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
797
798
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
799
func (s *Server) CopyModelHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
800
801
	var r api.CopyRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
802
803
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
804
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
805
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Patrick Devine's avatar
Patrick Devine committed
806
807
808
		return
	}

Michael Yang's avatar
Michael Yang committed
809
810
	src := model.ParseName(r.Source)
	if !src.IsValid() {
Michael Yang's avatar
Michael Yang committed
811
812
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("source %q is invalid", r.Source)})
		return
813
814
	}

Michael Yang's avatar
Michael Yang committed
815
816
	dst := model.ParseName(r.Destination)
	if !dst.IsValid() {
817
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("destination %q is invalid", r.Destination)})
Patrick Devine's avatar
Patrick Devine committed
818
819
		return
	}
Michael Yang's avatar
Michael Yang committed
820
821
822
823
824
825

	if err := CopyModel(src, dst); errors.Is(err, os.ErrNotExist) {
		c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model %q not found", r.Source)})
	} else if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
	}
Patrick Devine's avatar
Patrick Devine committed
826
827
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
828
func (s *Server) HeadBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
829
830
831
832
833
834
835
836
837
838
839
	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
840
	c.Status(http.StatusOK)
Michael Yang's avatar
Michael Yang committed
841
842
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
843
func (s *Server) CreateBlobHandler(c *gin.Context) {
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
	path, err := GetBlobsPath(c.Param("digest"))
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

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

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
	}

Michael Yang's avatar
Michael Yang committed
873
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
874
875
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
func isLocalIP(ip netip.Addr) bool {
	if interfaces, err := net.Interfaces(); err == nil {
		for _, iface := range interfaces {
			addrs, err := iface.Addrs()
			if err != nil {
				continue
			}

			for _, a := range addrs {
				if parsed, _, err := net.ParseCIDR(a.String()); err == nil {
					if parsed.String() == ip.String() {
						return true
					}
				}
			}
		}
	}

	return false
}

897
func allowedHost(host string) bool {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
898
	if host == "" || host == "localhost" {
899
900
901
902
903
904
905
906
		return true
	}

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

	var tlds = []string{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
907
908
909
		"localhost",
		"local",
		"internal",
910
	}
911

Jeffrey Morgan's avatar
Jeffrey Morgan committed
912
	// check if the host is a local TLD
913
914
915
916
917
918
	for _, tld := range tlds {
		if strings.HasSuffix(host, "."+tld) {
			return true
		}
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
919
	return false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
920
}
921

Jeffrey Morgan's avatar
Jeffrey Morgan committed
922
923
924
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
	return func(c *gin.Context) {
		if addr == nil {
925
926
927
928
			c.Next()
			return
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
929
		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
930
931
932
933
934
935
936
937
938
			c.Next()
			return
		}

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
939
		if addr, err := netip.ParseAddr(host); err == nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
940
			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
941
942
943
944
945
				c.Next()
				return
			}
		}

946
		if allowedHost(host) {
947
948
949
950
951
			if c.Request.Method == "OPTIONS" {
				c.AbortWithStatus(http.StatusNoContent)
				return
			}

952
953
954
955
956
957
			c.Next()
			return
		}

		c.AbortWithStatus(http.StatusForbidden)
	}
958
}
959

960
func (s *Server) GenerateRoutes() http.Handler {
Michael Yang's avatar
Michael Yang committed
961
962
	config := cors.DefaultConfig()
	config.AllowWildcard = true
963
	config.AllowBrowserExtensions = true
964
	config.AllowHeaders = []string{"Authorization", "Content-Type", "User-Agent", "Accept", "X-Requested-With"}
965
	config.AllowOrigins = envconfig.AllowOrigins
Michael Yang's avatar
Michael Yang committed
966

Bruce MacDonald's avatar
Bruce MacDonald committed
967
	r := gin.Default()
968
969
	r.Use(
		cors.New(config),
970
		allowedHostsMiddleware(s.addr),
971
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
972

Daniel Hiltgen's avatar
Daniel Hiltgen committed
973
974
975
976
977
978
979
980
981
982
983
	r.POST("/api/pull", s.PullModelHandler)
	r.POST("/api/generate", s.GenerateHandler)
	r.POST("/api/chat", s.ChatHandler)
	r.POST("/api/embeddings", s.EmbeddingsHandler)
	r.POST("/api/create", s.CreateModelHandler)
	r.POST("/api/push", s.PushModelHandler)
	r.POST("/api/copy", s.CopyModelHandler)
	r.DELETE("/api/delete", s.DeleteModelHandler)
	r.POST("/api/show", s.ShowModelHandler)
	r.POST("/api/blobs/:digest", s.CreateBlobHandler)
	r.HEAD("/api/blobs/:digest", s.HeadBlobHandler)
984
	r.GET("/api/ps", s.ProcessHandler)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
985

986
	// Compatibility endpoints
Daniel Hiltgen's avatar
Daniel Hiltgen committed
987
	r.POST("/v1/chat/completions", openai.Middleware(), s.ChatHandler)
988

Michael Yang's avatar
Michael Yang committed
989
990
991
992
993
	for _, method := range []string{http.MethodGet, http.MethodHead} {
		r.Handle(method, "/", func(c *gin.Context) {
			c.String(http.StatusOK, "Ollama is running")
		})

Daniel Hiltgen's avatar
Daniel Hiltgen committed
994
		r.Handle(method, "/api/tags", s.ListModelsHandler)
Michael Yang's avatar
Michael Yang committed
995
996
997
		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
998
999
	}

1000
1001
1002
1003
	return r
}

func Serve(ln net.Listener) error {
Michael Yang's avatar
Michael Yang committed
1004
	level := slog.LevelInfo
1005
	if envconfig.Debug {
Michael Yang's avatar
Michael Yang committed
1006
		level = slog.LevelDebug
1007
	}
Michael Yang's avatar
Michael Yang committed
1008

1009
	slog.Info("server config", "env", envconfig.AsMap())
Michael Yang's avatar
Michael Yang committed
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
	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))

1025
1026
1027
1028
1029
1030
1031
1032
	blobsDir, err := GetBlobsPath("")
	if err != nil {
		return err
	}
	if err := fixBlobs(blobsDir); err != nil {
		return err
	}

1033
	if !envconfig.NoPrune {
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
		// 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
		}
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1049
	ctx, done := context.WithCancel(context.Background())
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1050
1051
	schedCtx, schedDone := context.WithCancel(ctx)
	sched := InitScheduler(schedCtx)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1052
	s := &Server{addr: ln.Addr(), sched: sched}
1053
1054
	r := s.GenerateRoutes()

1055
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1056
	srvr := &http.Server{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1057
1058
1059
		Handler: r,
	}

1060
1061
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
1062
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
1063
1064
	go func() {
		<-signals
1065
		srvr.Close()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1066
		schedDone()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1067
		sched.unloadAllRunners()
1068
		gpu.Cleanup()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1069
		done()
1070
1071
	}()

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1072
	if err := llm.Init(); err != nil {
1073
1074
		return fmt.Errorf("unable to initialize llm library %w", err)
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1075

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1076
	s.sched.Run(schedCtx)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1077
1078
1079

	// At startup we retrieve GPU information so we can get log messages before loading a model
	// This will log warnings to the log in case we have problems with detected GPUs
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1080
1081
	gpus := gpu.GetGPUInfo()
	gpus.LogDetails()
1082

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1083
1084
1085
1086
1087
1088
1089
	err = srvr.Serve(ln)
	// If server is closed from the signal handler, wait for the ctx to be done
	// otherwise error out quickly
	if !errors.Is(err, http.ErrServerClosed) {
		return err
	}
	<-ctx.Done()
1090
	return nil
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1091
}
Michael Yang's avatar
Michael Yang committed
1092

1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
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
1118
func streamResponse(c *gin.Context, ch chan any) {
1119
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
1120
1121
1122
1123
1124
1125
1126
1127
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

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

1132
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
1133
1134
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
1135
			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1136
1137
1138
1139
1140
1141
			return false
		}

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

1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
func (s *Server) ProcessHandler(c *gin.Context) {
	models := []api.ModelResponse{}

	for _, v := range s.sched.loaded {
		model := v.model
		modelDetails := api.ModelDetails{
			Format:            model.Config.ModelFormat,
			Family:            model.Config.ModelFamily,
			Families:          model.Config.ModelFamilies,
			ParameterSize:     model.Config.ModelType,
			QuantizationLevel: model.Config.FileType,
		}

		mr := api.ModelResponse{
			Model:     model.ShortName,
			Name:      model.ShortName,
			Size:      int64(v.estimatedTotal),
			SizeVRAM:  int64(v.estimatedVRAM),
			Digest:    model.Digest,
			Details:   modelDetails,
			ExpiresAt: v.expiresAt,
		}
1165
1166
1167
1168
1169
1170
1171
1172
		// The scheduler waits to set expiresAt, so if a model is loading it's
		// possible that it will be set to the unix epoch. For those cases, just
		// calculate the time w/ the sessionDuration instead.
		var epoch time.Time
		if v.expiresAt == epoch {
			mr.ExpiresAt = time.Now().Add(v.sessionDuration)
		}

1173
1174
1175
1176
1177
1178
		models = append(models, mr)
	}

	c.JSON(http.StatusOK, api.ListResponse{Models: models})
}

1179
// ChatPrompt builds up a prompt from a series of messages for the currently `loaded` model
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1180
func chatPrompt(ctx context.Context, runner *runnerRef, template string, messages []api.Message, numCtx int) (string, error) {
1181
	encode := func(s string) ([]int, error) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1182
		return runner.llama.Tokenize(ctx, s)
1183
1184
	}

1185
	prompt, err := ChatPrompt(template, messages, numCtx, encode)
1186
1187
1188
1189
1190
1191
1192
	if err != nil {
		return "", err
	}

	return prompt, nil
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1193
func (s *Server) ChatHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
	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
	}

1217
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
1218
1219
	if err != nil {
		var pErr *fs.PathError
1220
		if errors.As(err, &pErr) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1221
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
1222
1223
1224
1225
1226
1227
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

1228
	if model.IsEmbedding() {
1229
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "embedding models do not support chat"})
1230
1231
1232
		return
	}

1233
1234
1235
1236
1237
	opts, err := modelOptions(model, req.Options)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
1238
1239
1240

	var sessionDuration time.Duration
	if req.KeepAlive == nil {
1241
		sessionDuration = getDefaultSessionDuration()
1242
1243
1244
1245
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1246
1247
1248
1249
1250
	rCh, eCh := s.sched.GetRunner(c.Request.Context(), model, opts, sessionDuration)
	var runner *runnerRef
	select {
	case runner = <-rCh:
	case err = <-eCh:
1251
		handleErrorResponse(c, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
1252
1253
1254
1255
1256
		return
	}

	checkpointLoaded := time.Now()

1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
	// if the first message is not a system message, then add the model's default system message
	if len(req.Messages) > 0 && req.Messages[0].Role != "system" {
		req.Messages = append([]api.Message{
			{
				Role:    "system",
				Content: model.System,
			},
		}, req.Messages...)
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1267
	prompt, err := chatPrompt(c.Request.Context(), runner, model.Template, req.Messages, opts.NumCtx)
Bruce MacDonald's avatar
Bruce MacDonald committed
1268
1269
1270
1271
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
1272

1273
	// an empty request loads the model
1274
	if len(req.Messages) == 0 || prompt == "" {
1275
		resp := api.ChatResponse{
1276
1277
1278
1279
1280
			CreatedAt:  time.Now().UTC(),
			Model:      req.Model,
			Done:       true,
			DoneReason: "load",
			Message:    api.Message{Role: "assistant"},
1281
1282
1283
1284
1285
		}
		c.JSON(http.StatusOK, resp)
		return
	}

1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
	// 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))
1304

Bruce MacDonald's avatar
Bruce MacDonald committed
1305
1306
1307
1308
1309
	ch := make(chan any)

	go func() {
		defer close(ch)

1310
		fn := func(r llm.CompletionResponse) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1311
1312

			resp := api.ChatResponse{
1313
1314
1315
1316
1317
				Model:      req.Model,
				CreatedAt:  time.Now().UTC(),
				Message:    api.Message{Role: "assistant", Content: r.Content},
				Done:       r.Done,
				DoneReason: r.DoneReason,
Bruce MacDonald's avatar
Bruce MacDonald committed
1318
1319
1320
1321
1322
1323
1324
1325
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}

1326
1327
1328
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
Bruce MacDonald's avatar
Bruce MacDonald committed
1329
1330
1331
1332
1333
			}

			ch <- resp
		}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1334
		if err := runner.llama.Completion(c.Request.Context(), llm.CompletionRequest{
1335
1336
			Prompt:  prompt,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
1337
			Images:  images,
1338
			Options: opts,
1339
		}, fn); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1340
1341
1342
1343
1344
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
1345
1346
		// Accumulate responses into the final response
		var final api.ChatResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
1347
1348
		var sb strings.Builder
		for resp := range ch {
1349
1350
			switch r := resp.(type) {
			case api.ChatResponse:
1351
				sb.WriteString(r.Message.Content)
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
				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
1364
1365
			}
		}
1366

1367
		final.Message = api.Message{Role: "assistant", Content: sb.String()}
1368
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
1369
1370
1371
1372
1373
		return
	}

	streamResponse(c, ch)
}
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385

func handleErrorResponse(c *gin.Context, err error) {
	if errors.Is(err, context.Canceled) {
		c.JSON(499, gin.H{"error": "request canceled"})
		return
	}
	if errors.Is(err, ErrMaxQueue) {
		c.JSON(http.StatusServiceUnavailable, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}