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

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

Michael Yang's avatar
Michael Yang committed
26
	"github.com/gin-contrib/cors"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
27
	"github.com/gin-gonic/gin"
28
	"golang.org/x/sync/errgroup"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
29

30
	"github.com/ollama/ollama/api"
31
	"github.com/ollama/ollama/discover"
32
	"github.com/ollama/ollama/envconfig"
33
	"github.com/ollama/ollama/llm"
34
	"github.com/ollama/ollama/model/mllama"
35
	"github.com/ollama/ollama/openai"
36
	"github.com/ollama/ollama/parser"
37
	"github.com/ollama/ollama/runners"
Michael Yang's avatar
Michael Yang committed
38
	"github.com/ollama/ollama/template"
39
	"github.com/ollama/ollama/types/errtypes"
Michael Yang's avatar
Michael Yang committed
40
	"github.com/ollama/ollama/types/model"
41
	"github.com/ollama/ollama/version"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
42
43
)

Michael Yang's avatar
Michael Yang committed
44
45
var mode string = gin.DebugMode

46
type Server struct {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
47
48
	addr  net.Addr
	sched *Scheduler
49
50
}

Michael Yang's avatar
Michael Yang committed
51
52
53
54
55
56
57
58
59
60
61
62
func init() {
	switch mode {
	case gin.DebugMode:
	case gin.ReleaseMode:
	case gin.TestMode:
	default:
		mode = gin.DebugMode
	}

	gin.SetMode(mode)
}

Michael Yang's avatar
lint  
Michael Yang committed
63
64
65
66
var (
	errRequired    = errors.New("is required")
	errBadTemplate = errors.New("template error")
)
Michael Yang's avatar
Michael Yang committed
67

68
69
70
71
72
73
74
75
76
77
78
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
79
80
}

Michael Yang's avatar
Michael Yang committed
81
82
83
// scheduleRunner schedules a runner after validating inputs such as capabilities and model options.
// It returns the allocated runner, model instance, and consolidated options if successful and error otherwise.
func (s *Server) scheduleRunner(ctx context.Context, name string, caps []Capability, requestOpts map[string]any, keepAlive *api.Duration) (llm.LlamaServer, *Model, *api.Options, error) {
Michael Yang's avatar
Michael Yang committed
84
	if name == "" {
Michael Yang's avatar
Michael Yang committed
85
		return nil, nil, nil, fmt.Errorf("model %w", errRequired)
Bruce MacDonald's avatar
Bruce MacDonald committed
86
87
	}

Michael Yang's avatar
Michael Yang committed
88
	model, err := GetModel(name)
Bruce MacDonald's avatar
Bruce MacDonald committed
89
	if err != nil {
Michael Yang's avatar
Michael Yang committed
90
		return nil, nil, nil, err
91
92
	}

Michael Yang's avatar
Michael Yang committed
93
	if err := model.CheckCapabilities(caps...); err != nil {
Michael Yang's avatar
Michael Yang committed
94
		return nil, nil, nil, fmt.Errorf("%s %w", name, err)
95
96
	}

Michael Yang's avatar
Michael Yang committed
97
	opts, err := modelOptions(model, requestOpts)
98
	if err != nil {
Michael Yang's avatar
Michael Yang committed
99
		return nil, nil, nil, err
100
101
	}

Michael Yang's avatar
Michael Yang committed
102
	runnerCh, errCh := s.sched.GetRunner(ctx, model, opts, keepAlive)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
103
104
	var runner *runnerRef
	select {
Michael Yang's avatar
Michael Yang committed
105
106
	case runner = <-runnerCh:
	case err = <-errCh:
Michael Yang's avatar
Michael Yang committed
107
		return nil, nil, nil, err
Bruce MacDonald's avatar
Bruce MacDonald committed
108
109
	}

Michael Yang's avatar
Michael Yang committed
110
	return runner.llama, model, &opts, nil
Michael Yang's avatar
Michael Yang committed
111
112
113
}

func (s *Server) GenerateHandler(c *gin.Context) {
114
	checkpointStart := time.Now()
Michael Yang's avatar
Michael Yang committed
115
116
117
118
119
120
	var req api.GenerateRequest
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	} else if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
121
122
123
		return
	}

124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
	name := model.ParseName(req.Model)
	if !name.IsValid() {
		// Ideally this is "invalid model name" but we're keeping with
		// what the API currently returns until we can change it.
		c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
		return
	}

	// We cannot currently consolidate this into GetModel because all we'll
	// induce infinite recursion given the current code structure.
	name, err := getExistingName(name)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
		return
	}

	model, err := GetModel(name.String())
141
142
	if err != nil {
		switch {
143
		case errors.Is(err, fs.ErrNotExist):
144
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
145
		case err.Error() == errtypes.InvalidModelNameErrMsg:
146
147
148
149
150
151
152
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

Patrick Devine's avatar
Patrick Devine committed
153
154
155
156
157
158
159
160
161
162
163
164
165
166
	// expire the runner
	if req.Prompt == "" && req.KeepAlive != nil && int(req.KeepAlive.Seconds()) == 0 {
		s.sched.expireRunner(model)

		c.JSON(http.StatusOK, api.GenerateResponse{
			Model:      req.Model,
			CreatedAt:  time.Now().UTC(),
			Response:   "",
			Done:       true,
			DoneReason: "unload",
		})
		return
	}

167
	if req.Raw && (req.Template != "" || req.System != "" || len(req.Context) > 0) {
Michael Yang's avatar
Michael Yang committed
168
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "raw mode does not support template, system, or context"})
Michael Yang's avatar
Michael Yang committed
169
170
171
		return
	}

Michael Yang's avatar
Michael Yang committed
172
	caps := []Capability{CapabilityCompletion}
173
174
175
176
	if req.Suffix != "" {
		caps = append(caps, CapabilityInsert)
	}

177
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), caps, req.Options, req.KeepAlive)
Michael Yang's avatar
Michael Yang committed
178
179
180
181
	if errors.Is(err, errCapabilityCompletion) {
		c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("%q does not support generate", req.Model)})
		return
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
182
183
184
185
		handleScheduleError(c, req.Model, err)
		return
	}

186
187
	checkpointLoaded := time.Now()

188
	// load the model
Michael Yang's avatar
Michael Yang committed
189
190
191
192
193
194
195
	if req.Prompt == "" {
		c.JSON(http.StatusOK, api.GenerateResponse{
			Model:      req.Model,
			CreatedAt:  time.Now().UTC(),
			Done:       true,
			DoneReason: "load",
		})
Michael Yang's avatar
Michael Yang committed
196
197
		return
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
198

199
200
201
202
203
204
	isMllama := checkMllamaModelFamily(model)
	if isMllama && len(req.Images) > 1 {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "this model only supports one image: more than one image sent"})
		return
	}

Michael Yang's avatar
Michael Yang committed
205
206
	images := make([]llm.ImageData, len(req.Images))
	for i := range req.Images {
207
		if isMllama {
208
			data, opts, err := mllama.Preprocess(bytes.NewReader(req.Images[i]))
209
210
211
212
213
			if err != nil {
				c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "error processing image"})
				return
			}

214
215
216
217
218
219
			ar, ok := opts["aspectRatioIndex"].(int)
			if !ok {
				c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "error processing image"})
				return
			}

220
221
222
223
224
225
226
			buf := new(bytes.Buffer)
			err = binary.Write(buf, binary.LittleEndian, data)
			if err != nil {
				c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "error processing image"})
				return
			}

227
			images[i] = llm.ImageData{ID: i, Data: buf.Bytes(), AspectRatioID: ar}
228
229
230
		} else {
			images[i] = llm.ImageData{ID: i, Data: req.Images[i]}
		}
Michael Yang's avatar
Michael Yang committed
231
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
232

Michael Yang's avatar
Michael Yang committed
233
234
	prompt := req.Prompt
	if !req.Raw {
Michael Yang's avatar
Michael Yang committed
235
		tmpl := m.Template
Michael Yang's avatar
Michael Yang committed
236
237
238
239
240
241
242
243
		if req.Template != "" {
			tmpl, err = template.Parse(req.Template)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}

244
245
246
247
248
249
250
251
252
253
254
255
		var values template.Values
		if req.Suffix != "" {
			values.Prompt = prompt
			values.Suffix = req.Suffix
		} else {
			var msgs []api.Message
			if req.System != "" {
				msgs = append(msgs, api.Message{Role: "system", Content: req.System})
			} else if m.System != "" {
				msgs = append(msgs, api.Message{Role: "system", Content: m.System})
			}

Michael Yang's avatar
Michael Yang committed
256
257
258
259
			if req.Context == nil {
				msgs = append(msgs, m.Messages...)
			}

260
			for _, i := range images {
261
				imgPrompt := ""
262
				if isMllama {
263
					imgPrompt = "<|image|>"
264
				}
265
				msgs = append(msgs, api.Message{Role: "user", Content: fmt.Sprintf("[img-%d]"+imgPrompt, i.ID)})
266
267
268
269
270
			}

			values.Messages = append(msgs, api.Message{Role: "user", Content: req.Prompt})
		}

Michael Yang's avatar
Michael Yang committed
271
272
		var b bytes.Buffer
		if req.Context != nil {
273
			slog.Warn("the context field is deprecated and will be removed in a future version of Ollama")
274
			s, err := r.Detokenize(c.Request.Context(), req.Context)
Michael Yang's avatar
Michael Yang committed
275
276
277
278
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
279
			b.WriteString(s)
Michael Yang's avatar
Michael Yang committed
280
		}
281
282
283
284
285
286
287

		if err := tmpl.Execute(&b, values); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		prompt = b.String()
Bruce MacDonald's avatar
Bruce MacDonald committed
288
289
	}

290
	slog.Debug("generate request", "images", len(images), "prompt", prompt)
291

Bruce MacDonald's avatar
Bruce MacDonald committed
292
293
	ch := make(chan any)
	go func() {
294
295
		// TODO (jmorganca): avoid building the response twice both here and below
		var sb strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
296
		defer close(ch)
Michael Yang's avatar
Michael Yang committed
297
		if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
Michael Yang's avatar
Michael Yang committed
298
299
			Prompt:  prompt,
			Images:  images,
300
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
301
			Options: opts,
302
303
		}, func(cr llm.CompletionResponse) {
			res := api.GenerateResponse{
304
305
				Model:      req.Model,
				CreatedAt:  time.Now().UTC(),
306
307
308
				Response:   cr.Content,
				Done:       cr.Done,
				DoneReason: cr.DoneReason,
Bruce MacDonald's avatar
Bruce MacDonald committed
309
				Metrics: api.Metrics{
310
311
312
313
					PromptEvalCount:    cr.PromptEvalCount,
					PromptEvalDuration: cr.PromptEvalDuration,
					EvalCount:          cr.EvalCount,
					EvalDuration:       cr.EvalDuration,
Bruce MacDonald's avatar
Bruce MacDonald committed
314
				},
Bruce MacDonald's avatar
Bruce MacDonald committed
315
			}
316
317
318
319
320
321
322
323
324
325

			if _, err := sb.WriteString(cr.Content); err != nil {
				ch <- gin.H{"error": err.Error()}
			}

			if cr.Done {
				res.TotalDuration = time.Since(checkpointStart)
				res.LoadDuration = checkpointLoaded.Sub(checkpointStart)

				if !req.Raw {
326
					tokens, err := r.Tokenize(c.Request.Context(), prompt+sb.String())
327
328
329
330
					if err != nil {
						ch <- gin.H{"error": err.Error()}
						return
					}
331
					res.Context = tokens
332
333
334
335
				}
			}

			ch <- res
Michael Yang's avatar
Michael Yang committed
336
		}); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
337
338
339
340
341
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
Michael Yang's avatar
Michael Yang committed
342
		var r api.GenerateResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
343
		var sb strings.Builder
Michael Yang's avatar
Michael Yang committed
344
345
		for rr := range ch {
			switch t := rr.(type) {
346
			case api.GenerateResponse:
Michael Yang's avatar
Michael Yang committed
347
348
				sb.WriteString(t.Response)
				r = t
349
			case gin.H:
Michael Yang's avatar
Michael Yang committed
350
351
352
				msg, ok := t["error"].(string)
				if !ok {
					msg = "unexpected error format in response"
353
				}
Michael Yang's avatar
Michael Yang committed
354
355
356

				c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
				return
357
			default:
Michael Yang's avatar
Michael Yang committed
358
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
Bruce MacDonald's avatar
Bruce MacDonald committed
359
360
361
				return
			}
		}
362

Michael Yang's avatar
Michael Yang committed
363
364
		r.Response = sb.String()
		c.JSON(http.StatusOK, r)
Bruce MacDonald's avatar
Bruce MacDonald committed
365
366
367
368
369
370
		return
	}

	streamResponse(c, ch)
}

371
func (s *Server) EmbedHandler(c *gin.Context) {
372
	checkpointStart := time.Now()
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
	var req api.EmbedRequest
	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
	}

	truncate := true

	if req.Truncate != nil && !*req.Truncate {
		truncate = false
	}

	var input []string

	switch i := req.Input.(type) {
	case string:
		if len(i) > 0 {
			input = append(input, i)
		}
	case []any:
		for _, v := range i {
			if _, ok := v.(string); !ok {
				c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid input type"})
				return
			}
			input = append(input, v.(string))
		}
	default:
406
407
408
409
		if req.Input != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid input type"})
			return
		}
410
411
	}

412
413
414
415
416
417
418
	name, err := getExistingName(model.ParseName(req.Model))
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
		return
	}

	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), []Capability{}, req.Options, req.KeepAlive)
419
420
421
422
423
	if err != nil {
		handleScheduleError(c, req.Model, err)
		return
	}

424
425
	checkpointLoaded := time.Now()

426
427
428
429
430
	if len(input) == 0 {
		c.JSON(http.StatusOK, api.EmbedResponse{Model: req.Model, Embeddings: [][]float32{}})
		return
	}

431
432
433
434
435
436
	kvData, err := getKVData(m.ModelPath, false)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

437
	var count int
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
	for i, s := range input {
		tokens, err := r.Tokenize(c.Request.Context(), s)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		ctxLen := min(opts.NumCtx, int(kvData.ContextLength()))
		if len(tokens) > ctxLen {
			if !truncate {
				c.JSON(http.StatusBadRequest, gin.H{"error": "input length exceeds maximum context length"})
				return
			}

			tokens = tokens[:ctxLen]
			s, err = r.Detokenize(c.Request.Context(), tokens)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}

460
461
		count += len(tokens)

462
463
		input[i] = s
	}
464
465
466
467
468
469
470
471
472
473
474
475

	var g errgroup.Group
	embeddings := make([][]float32, len(input))
	for i, text := range input {
		g.Go(func() error {
			embedding, err := r.Embedding(c.Request.Context(), text)
			if err != nil {
				return err
			}
			embeddings[i] = normalize(embedding)
			return nil
		})
476
477
	}

478
479
480
481
	if err := g.Wait(); err != nil {
		slog.Error("embedding generation failed", "error", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Errorf("failed to generate embeddings: %v", err)})
		return
482
483
484
	}

	resp := api.EmbedResponse{
485
		Model:           req.Model,
486
		Embeddings:      embeddings,
487
488
		TotalDuration:   time.Since(checkpointStart),
		LoadDuration:    checkpointLoaded.Sub(checkpointStart),
489
		PromptEvalCount: count,
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
	}
	c.JSON(http.StatusOK, resp)
}

func normalize(vec []float32) []float32 {
	var sum float32
	for _, v := range vec {
		sum += v * v
	}

	norm := float32(0.0)
	if sum > 0 {
		norm = float32(1.0 / math.Sqrt(float64(sum)))
	}

	for i := range vec {
		vec[i] *= norm
	}
	return vec
}

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

521
522
523
524
525
526
527
	name := model.ParseName(req.Model)
	if !name.IsValid() {
		c.JSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
	}

	r, _, _, err := s.scheduleRunner(c.Request.Context(), name.String(), []Capability{}, req.Options, req.KeepAlive)
Bruce MacDonald's avatar
Bruce MacDonald committed
528
	if err != nil {
Michael Yang's avatar
Michael Yang committed
529
		handleScheduleError(c, req.Model, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
530
531
532
		return
	}

533
534
535
	// an empty request loads the model
	if req.Prompt == "" {
		c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: []float64{}})
Bruce MacDonald's avatar
Bruce MacDonald committed
536
537
538
		return
	}

539
	embedding, err := r.Embedding(c.Request.Context(), req.Prompt)
Bruce MacDonald's avatar
Bruce MacDonald committed
540
	if err != nil {
541
		slog.Info(fmt.Sprintf("embedding generation failed: %v", err))
542
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Errorf("failed to generate embedding: %v", err)})
Bruce MacDonald's avatar
Bruce MacDonald committed
543
544
545
		return
	}

546
547
548
	var e []float64
	for _, v := range embedding {
		e = append(e, float64(v))
549
550
551
	}

	resp := api.EmbeddingResponse{
552
		Embedding: e,
553
554
	}
	c.JSON(http.StatusOK, resp)
Bruce MacDonald's avatar
Bruce MacDonald committed
555
556
}

557
func (s *Server) PullHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
558
	var req api.PullRequest
Michael Yang's avatar
Michael Yang committed
559
560
561
562
563
564
565
	err := c.ShouldBindJSON(&req)
	switch {
	case errors.Is(err, io.EOF):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	case err != nil:
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
566
567
568
		return
	}

569
570
	name := model.ParseName(cmp.Or(req.Model, req.Name))
	if !name.IsValid() {
571
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": errtypes.InvalidModelNameErrMsg})
572
573
574
		return
	}

575
576
	name, err = getExistingName(name)
	if err != nil {
577
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
578
579
580
		return
	}

581
582
583
	ch := make(chan any)
	go func() {
		defer close(ch)
584
585
		fn := func(r api.ProgressResponse) {
			ch <- r
586
		}
587

Michael Yang's avatar
Michael Yang committed
588
		regOpts := &registryOptions{
589
590
591
			Insecure: req.Insecure,
		}

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

595
		if err := PullModel(ctx, name.DisplayShortest(), regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
596
			ch <- gin.H{"error": err.Error()}
597
598
599
		}
	}()

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

605
606
607
	streamResponse(c, ch)
}

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

620
	var mname string
Michael Yang's avatar
Michael Yang committed
621
	if req.Model != "" {
622
		mname = req.Model
Michael Yang's avatar
Michael Yang committed
623
	} else if req.Name != "" {
624
		mname = req.Name
Michael Yang's avatar
Michael Yang committed
625
626
	} else {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
627
628
629
		return
	}

630
631
632
	ch := make(chan any)
	go func() {
		defer close(ch)
633
634
		fn := func(r api.ProgressResponse) {
			ch <- r
635
		}
636

Michael Yang's avatar
Michael Yang committed
637
		regOpts := &registryOptions{
638
639
640
			Insecure: req.Insecure,
		}

Michael Yang's avatar
Michael Yang committed
641
642
643
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

644
645
646
647
648
649
650
		name, err := getExistingName(model.ParseName(mname))
		if err != nil {
			ch <- gin.H{"error": err.Error()}
			return
		}

		if err := PushModel(ctx, name.DisplayShortest(), regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
651
			ch <- gin.H{"error": err.Error()}
652
653
654
		}
	}()

655
656
657
658
659
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

660
661
662
	streamResponse(c, ch)
}

663
664
665
666
// getExistingName searches the models directory for the longest prefix match of
// the input name and returns the input name with all existing parts replaced
// with each part found. If no parts are found, the input name is returned as
// is.
667
668
669
func getExistingName(n model.Name) (model.Name, error) {
	var zero model.Name
	existing, err := Manifests(true)
670
	if err != nil {
671
		return zero, err
672
	}
673
	var set model.Name // tracks parts already canonicalized
674
	for e := range existing {
675
676
677
678
679
680
681
682
683
684
685
		if set.Host == "" && strings.EqualFold(e.Host, n.Host) {
			n.Host = e.Host
		}
		if set.Namespace == "" && strings.EqualFold(e.Namespace, n.Namespace) {
			n.Namespace = e.Namespace
		}
		if set.Model == "" && strings.EqualFold(e.Model, n.Model) {
			n.Model = e.Model
		}
		if set.Tag == "" && strings.EqualFold(e.Tag, n.Tag) {
			n.Tag = e.Tag
686
687
		}
	}
688
	return n, nil
689
690
}

691
func (s *Server) CreateHandler(c *gin.Context) {
692
693
	var r api.CreateRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
694
695
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
696
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
697
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
698
		return
699
700
	}

701
	name := model.ParseName(cmp.Or(r.Model, r.Name))
Michael Yang's avatar
Michael Yang committed
702
	if !name.IsValid() {
703
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": errtypes.InvalidModelNameErrMsg})
704
705
706
		return
	}

707
708
	name, err := getExistingName(name)
	if err != nil {
709
710
711
712
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

713
	if r.Path == "" && r.Modelfile == "" {
714
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or Modelfile are required"})
Michael Yang's avatar
Michael Yang committed
715
716
		return
	}
Michael Yang's avatar
Michael Yang committed
717

718
719
720
	var sr io.Reader = strings.NewReader(r.Modelfile)
	if r.Path != "" && r.Modelfile == "" {
		f, err := os.Open(r.Path)
Michael Yang's avatar
Michael Yang committed
721
722
723
724
		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
725
		defer f.Close()
Michael Yang's avatar
Michael Yang committed
726

727
		sr = f
Michael Yang's avatar
Michael Yang committed
728
	}
Michael Yang's avatar
Michael Yang committed
729

730
	f, err := parser.ParseFile(sr)
Michael Yang's avatar
Michael Yang committed
731
732
733
734
735
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
736
	ch := make(chan any)
Michael Yang's avatar
Michael Yang committed
737
738
	go func() {
		defer close(ch)
739
740
		fn := func(resp api.ProgressResponse) {
			ch <- resp
741
742
		}

743
744
745
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

746
		quantization := cmp.Or(r.Quantize, r.Quantization)
Josh's avatar
Josh committed
747
748
749
		if err := CreateModel(ctx, name, filepath.Dir(r.Path), strings.ToUpper(quantization), f, fn); errors.Is(err, errBadTemplate) {
			ch <- gin.H{"error": err.Error(), "status": http.StatusBadRequest}
		} else if err != nil {
Michael Yang's avatar
Michael Yang committed
750
			ch <- gin.H{"error": err.Error()}
751
		}
Michael Yang's avatar
Michael Yang committed
752
	}()
Michael Yang's avatar
Michael Yang committed
753

754
	if r.Stream != nil && !*r.Stream {
755
756
757
758
		waitForStream(c, ch)
		return
	}

Michael Yang's avatar
Michael Yang committed
759
	streamResponse(c, ch)
Bruce MacDonald's avatar
Bruce MacDonald committed
760
761
}

762
func (s *Server) DeleteHandler(c *gin.Context) {
763
764
	var r api.DeleteRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
765
766
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
767
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
768
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
769
770
771
		return
	}

772
773
774
	n := model.ParseName(cmp.Or(r.Model, r.Name))
	if !n.IsValid() {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("name %q is invalid", cmp.Or(r.Model, r.Name))})
775
776
		return
	}
Michael Yang's avatar
Michael Yang committed
777

778
779
780
781
782
783
	n, err := getExistingName(n)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", cmp.Or(r.Model, r.Name))})
		return
	}

784
	m, err := ParseNamedManifest(n)
Michael Yang's avatar
Michael Yang committed
785
	if err != nil {
786
787
788
789
790
791
		switch {
		case os.IsNotExist(err):
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", cmp.Or(r.Model, r.Name))})
		default:
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
Michael Yang's avatar
Michael Yang committed
792
793
794
		return
	}

795
	if err := m.Remove(); err != nil {
Michael Yang's avatar
Michael Yang committed
796
797
798
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
799
800
801
802
803

	if err := m.RemoveLayers(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
804
805
}

806
func (s *Server) ShowHandler(c *gin.Context) {
Patrick Devine's avatar
Patrick Devine committed
807
	var req api.ShowRequest
Michael Yang's avatar
Michael Yang committed
808
809
810
811
812
813
814
	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
815
816
817
		return
	}

Michael Yang's avatar
Michael Yang committed
818
	if req.Model != "" {
Michael Yang's avatar
Michael Yang committed
819
		// noop
Michael Yang's avatar
Michael Yang committed
820
	} else if req.Name != "" {
Michael Yang's avatar
Michael Yang committed
821
		req.Model = req.Name
Michael Yang's avatar
Michael Yang committed
822
	} else {
823
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
824
825
826
		return
	}

827
	resp, err := GetModelInfo(req)
Patrick Devine's avatar
Patrick Devine committed
828
	if err != nil {
829
830
		switch {
		case os.IsNotExist(err):
Michael Yang's avatar
Michael Yang committed
831
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
832
		case err.Error() == errtypes.InvalidModelNameErrMsg:
833
834
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
Patrick Devine's avatar
Patrick Devine committed
835
836
837
838
839
840
841
842
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

	c.JSON(http.StatusOK, resp)
}

843
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
844
845
846
847
848
849
850
851
852
853
	name := model.ParseName(req.Model)
	if !name.IsValid() {
		return nil, errModelPathInvalid
	}
	name, err := getExistingName(name)
	if err != nil {
		return nil, err
	}

	m, err := GetModel(name.String())
Patrick Devine's avatar
Patrick Devine committed
854
855
856
857
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
858
	modelDetails := api.ModelDetails{
859
860
861
862
863
864
		ParentModel:       m.ParentModel,
		Format:            m.Config.ModelFormat,
		Family:            m.Config.ModelFamily,
		Families:          m.Config.ModelFamilies,
		ParameterSize:     m.Config.ModelType,
		QuantizationLevel: m.Config.FileType,
Patrick Devine's avatar
Patrick Devine committed
865
866
	}

867
	if req.System != "" {
868
		m.System = req.System
869
870
	}

Michael Yang's avatar
Michael Yang committed
871
872
873
	msgs := make([]api.Message, len(m.Messages))
	for i, msg := range m.Messages {
		msgs[i] = api.Message{Role: msg.Role, Content: msg.Content}
874
875
	}

876
	manifest, err := ParseNamedManifest(name)
877
878
879
880
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
881
	resp := &api.ShowResponse{
882
883
		License:    strings.Join(m.License, "\n"),
		System:     m.System,
Michael Yang's avatar
Michael Yang committed
884
		Template:   m.Template.String(),
885
886
887
		Details:    modelDetails,
		Messages:   msgs,
		ModifiedAt: manifest.fi.ModTime(),
Patrick Devine's avatar
Patrick Devine committed
888
889
890
891
	}

	var params []string
	cs := 30
892
	for k, v := range m.Options {
Patrick Devine's avatar
Patrick Devine committed
893
894
895
		switch val := v.(type) {
		case []interface{}:
			for _, nv := range val {
Patrick Devine's avatar
Patrick Devine committed
896
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
Patrick Devine's avatar
Patrick Devine committed
897
			}
Patrick Devine's avatar
Patrick Devine committed
898
899
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
Patrick Devine's avatar
Patrick Devine committed
900
901
902
903
		}
	}
	resp.Parameters = strings.Join(params, "\n")

904
905
	for k, v := range req.Options {
		if _, ok := req.Options[k]; ok {
906
			m.Options[k] = v
907
908
909
		}
	}

910
	var sb strings.Builder
911
	fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"")
912
	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
913
914
	fmt.Fprintf(&sb, "# FROM %s\n\n", m.ShortName)
	fmt.Fprint(&sb, m.String())
915
	resp.Modelfile = sb.String()
916

917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
	kvData, err := getKVData(m.ModelPath, req.Verbose)
	if err != nil {
		return nil, err
	}
	delete(kvData, "general.name")
	delete(kvData, "tokenizer.chat_template")
	resp.ModelInfo = kvData

	if len(m.ProjectorPaths) > 0 {
		projectorData, err := getKVData(m.ProjectorPaths[0], req.Verbose)
		if err != nil {
			return nil, err
		}
		resp.ProjectorInfo = projectorData
	}

Patrick Devine's avatar
Patrick Devine committed
933
934
935
	return resp, nil
}

936
func getKVData(digest string, verbose bool) (llm.KV, error) {
937
938
939
940
941
	maxArraySize := 0
	if verbose {
		maxArraySize = -1
	}
	kvData, err := llm.LoadModel(digest, maxArraySize)
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
	if err != nil {
		return nil, err
	}

	kv := kvData.KV()

	if !verbose {
		for k := range kv {
			if t, ok := kv[k].([]any); len(t) > 5 && ok {
				kv[k] = []any{}
			}
		}
	}

	return kv, nil
}

959
func (s *Server) ListHandler(c *gin.Context) {
960
	ms, err := Manifests(true)
Patrick Devine's avatar
Patrick Devine committed
961
962
963
964
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
965

966
	models := []api.ListModelResponse{}
967
968
	for n, m := range ms {
		var cf ConfigV2
969
970
971
972
973
974
975
976
977
978
979
980
981

		if m.Config.Digest != "" {
			f, err := m.Config.Open()
			if err != nil {
				slog.Warn("bad manifest filepath", "name", n, "error", err)
				continue
			}
			defer f.Close()

			if err := json.NewDecoder(f).Decode(&cf); err != nil {
				slog.Warn("bad manifest config", "name", n, "error", err)
				continue
			}
Patrick Devine's avatar
Patrick Devine committed
982
		}
Michael Yang's avatar
Michael Yang committed
983

984
		// tag should never be masked
985
		models = append(models, api.ListModelResponse{
986
987
988
989
990
991
992
993
994
995
996
997
998
			Model:      n.DisplayShortest(),
			Name:       n.DisplayShortest(),
			Size:       m.Size(),
			Digest:     m.digest,
			ModifiedAt: m.fi.ModTime(),
			Details: api.ModelDetails{
				Format:            cf.ModelFormat,
				Family:            cf.ModelFamily,
				Families:          cf.ModelFamilies,
				ParameterSize:     cf.ModelType,
				QuantizationLevel: cf.FileType,
			},
		})
Patrick Devine's avatar
Patrick Devine committed
999
1000
	}

1001
	slices.SortStableFunc(models, func(i, j api.ListModelResponse) int {
1002
1003
1004
1005
		// most recently modified first
		return cmp.Compare(j.ModifiedAt.Unix(), i.ModifiedAt.Unix())
	})

Michael Yang's avatar
Michael Yang committed
1006
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
1007
1008
}

1009
func (s *Server) CopyHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1010
1011
	var r api.CopyRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
1012
1013
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
1014
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
1015
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Patrick Devine's avatar
Patrick Devine committed
1016
1017
1018
		return
	}

Michael Yang's avatar
Michael Yang committed
1019
1020
	src := model.ParseName(r.Source)
	if !src.IsValid() {
Michael Yang's avatar
Michael Yang committed
1021
1022
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("source %q is invalid", r.Source)})
		return
1023
	}
1024
1025
1026
1027
1028
	src, err := getExistingName(src)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
1029

Michael Yang's avatar
Michael Yang committed
1030
1031
	dst := model.ParseName(r.Destination)
	if !dst.IsValid() {
1032
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("destination %q is invalid", r.Destination)})
Patrick Devine's avatar
Patrick Devine committed
1033
1034
		return
	}
1035
1036
	dst, err = getExistingName(dst)
	if err != nil {
1037
1038
1039
1040
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
1041
1042
1043
1044
1045
	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
1046
1047
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1048
func (s *Server) HeadBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
	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
1060
	c.Status(http.StatusOK)
Michael Yang's avatar
Michael Yang committed
1061
1062
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1063
func (s *Server) CreateBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1064
1065
	if ib, ok := intermediateBlobs[c.Param("digest")]; ok {
		p, err := GetBlobsPath(ib)
1066
1067
1068
1069
1070
1071
		if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		if _, err := os.Stat(p); errors.Is(err, os.ErrNotExist) {
Michael Yang's avatar
Michael Yang committed
1072
1073
			slog.Info("evicting intermediate blob which no longer exists", "digest", ib)
			delete(intermediateBlobs, c.Param("digest"))
1074
1075
1076
1077
1078
1079
1080
1081
1082
		} else if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		} else {
			c.Status(http.StatusOK)
			return
		}
	}

1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
	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
	}

1101
	layer, err := NewLayer(c.Request.Body, "")
Michael Yang's avatar
Michael Yang committed
1102
1103
1104
1105
1106
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

1107
1108
	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
1109
1110
1111
		return
	}

Michael Yang's avatar
Michael Yang committed
1112
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
1113
1114
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
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
}

1136
func allowedHost(host string) bool {
1137
1138
	host = strings.ToLower(host)

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1139
	if host == "" || host == "localhost" {
1140
1141
1142
		return true
	}

1143
	if hostname, err := os.Hostname(); err == nil && host == strings.ToLower(hostname) {
1144
1145
1146
		return true
	}

Michael Yang's avatar
lint  
Michael Yang committed
1147
	tlds := []string{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1148
1149
1150
		"localhost",
		"local",
		"internal",
1151
	}
1152

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1153
	// check if the host is a local TLD
1154
1155
1156
1157
1158
1159
	for _, tld := range tlds {
		if strings.HasSuffix(host, "."+tld) {
			return true
		}
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1160
	return false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1161
}
1162

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1163
1164
1165
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
	return func(c *gin.Context) {
		if addr == nil {
1166
1167
1168
1169
			c.Next()
			return
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1170
		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
1171
1172
1173
1174
1175
1176
1177
1178
1179
			c.Next()
			return
		}

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1180
		if addr, err := netip.ParseAddr(host); err == nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1181
			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1182
1183
1184
1185
1186
				c.Next()
				return
			}
		}

1187
		if allowedHost(host) {
Michael Yang's avatar
lint  
Michael Yang committed
1188
			if c.Request.Method == http.MethodOptions {
1189
1190
1191
1192
				c.AbortWithStatus(http.StatusNoContent)
				return
			}

1193
1194
1195
1196
1197
1198
			c.Next()
			return
		}

		c.AbortWithStatus(http.StatusForbidden)
	}
1199
}
1200

1201
func (s *Server) GenerateRoutes() http.Handler {
Michael Yang's avatar
Michael Yang committed
1202
1203
	config := cors.DefaultConfig()
	config.AllowWildcard = true
1204
	config.AllowBrowserExtensions = true
1205
	config.AllowHeaders = []string{"Authorization", "Content-Type", "User-Agent", "Accept", "X-Requested-With"}
1206
	openAIProperties := []string{"lang", "package-version", "os", "arch", "retry-count", "runtime", "runtime-version", "async"}
royjhan's avatar
royjhan committed
1207
1208
1209
	for _, prop := range openAIProperties {
		config.AllowHeaders = append(config.AllowHeaders, "x-stainless-"+prop)
	}
Michael Yang's avatar
origins  
Michael Yang committed
1210
	config.AllowOrigins = envconfig.Origins()
Michael Yang's avatar
Michael Yang committed
1211

Bruce MacDonald's avatar
Bruce MacDonald committed
1212
	r := gin.Default()
1213
1214
	r.Use(
		cors.New(config),
1215
		allowedHostsMiddleware(s.addr),
1216
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
1217

1218
	r.POST("/api/pull", s.PullHandler)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1219
1220
	r.POST("/api/generate", s.GenerateHandler)
	r.POST("/api/chat", s.ChatHandler)
1221
	r.POST("/api/embed", s.EmbedHandler)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1222
	r.POST("/api/embeddings", s.EmbeddingsHandler)
1223
1224
1225
1226
1227
	r.POST("/api/create", s.CreateHandler)
	r.POST("/api/push", s.PushHandler)
	r.POST("/api/copy", s.CopyHandler)
	r.DELETE("/api/delete", s.DeleteHandler)
	r.POST("/api/show", s.ShowHandler)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1228
1229
	r.POST("/api/blobs/:digest", s.CreateBlobHandler)
	r.HEAD("/api/blobs/:digest", s.HeadBlobHandler)
1230
	r.GET("/api/ps", s.PsHandler)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1231

1232
	// Compatibility endpoints
1233
	r.POST("/v1/chat/completions", openai.ChatMiddleware(), s.ChatHandler)
1234
	r.POST("/v1/completions", openai.CompletionsMiddleware(), s.GenerateHandler)
1235
	r.POST("/v1/embeddings", openai.EmbeddingsMiddleware(), s.EmbedHandler)
1236
1237
	r.GET("/v1/models", openai.ListMiddleware(), s.ListHandler)
	r.GET("/v1/models/:model", openai.RetrieveMiddleware(), s.ShowHandler)
1238

Michael Yang's avatar
Michael Yang committed
1239
1240
1241
1242
1243
	for _, method := range []string{http.MethodGet, http.MethodHead} {
		r.Handle(method, "/", func(c *gin.Context) {
			c.String(http.StatusOK, "Ollama is running")
		})

1244
		r.Handle(method, "/api/tags", s.ListHandler)
Michael Yang's avatar
Michael Yang committed
1245
1246
1247
		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
1248
1249
	}

1250
1251
1252
1253
	return r
}

func Serve(ln net.Listener) error {
Michael Yang's avatar
Michael Yang committed
1254
	level := slog.LevelInfo
Michael Yang's avatar
Michael Yang committed
1255
	if envconfig.Debug() {
Michael Yang's avatar
Michael Yang committed
1256
		level = slog.LevelDebug
1257
	}
Michael Yang's avatar
Michael Yang committed
1258

1259
	slog.Info("server config", "env", envconfig.Values())
Michael Yang's avatar
Michael Yang committed
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
	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))

1275
1276
1277
1278
1279
1280
1281
1282
	blobsDir, err := GetBlobsPath("")
	if err != nil {
		return err
	}
	if err := fixBlobs(blobsDir); err != nil {
		return err
	}

Michael Yang's avatar
bool  
Michael Yang committed
1283
	if !envconfig.NoPrune() {
1284
1285
1286
1287
1288
1289
1290
		if _, err := Manifests(false); err != nil {
			slog.Warn("corrupt manifests detected, skipping prune operation.  Re-pull or delete to clear", "error", err)
		} else {
			// clean up unused layers and manifests
			if err := PruneLayers(); err != nil {
				return err
			}
1291

1292
1293
1294
1295
			manifestsPath, err := GetManifestPath()
			if err != nil {
				return err
			}
1296

1297
1298
1299
			if err := PruneDirectory(manifestsPath); err != nil {
				return err
			}
1300
1301
1302
		}
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1303
	ctx, done := context.WithCancel(context.Background())
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1304
1305
	schedCtx, schedDone := context.WithCancel(ctx)
	sched := InitScheduler(schedCtx)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1306
	s := &Server{addr: ln.Addr(), sched: sched}
1307
1308

	http.Handle("/", s.GenerateRoutes())
1309

1310
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1311
	srvr := &http.Server{
1312
1313
1314
1315
1316
1317
1318
1319
1320
		// Use http.DefaultServeMux so we get net/http/pprof for
		// free.
		//
		// TODO(bmizerany): Decide if we want to make this
		// configurable so it is not exposed by default, or allow
		// users to bind it to a different port. This was a quick
		// and easy way to get pprof, but it may not be the best
		// way.
		Handler: nil,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1321
1322
	}

1323
1324
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
1325
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
1326
1327
	go func() {
		<-signals
1328
		srvr.Close()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1329
		schedDone()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1330
		sched.unloadAllRunners()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1331
		done()
1332
1333
	}()

1334
1335
1336
1337
	// Locate and log what runners are present at startup
	var runnerNames []string
	for v := range runners.GetAvailableServers() {
		runnerNames = append(runnerNames, v)
1338
	}
1339
1340
	slog.Info("Dynamic LLM libraries", "runners", runnerNames)
	slog.Debug("Override detection logic by setting OLLAMA_LLM_LIBRARY")
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1341

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1342
	s.sched.Run(schedCtx)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1343
1344
1345

	// 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
1346
	gpus := discover.GetGPUInfo()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1347
	gpus.LogDetails()
1348

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1349
1350
1351
1352
1353
1354
1355
	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()
1356
	return nil
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1357
}
Michael Yang's avatar
Michael Yang committed
1358

1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
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:
Josh's avatar
Josh committed
1369
1370
1371
1372
			status, ok := r["status"].(int)
			if !ok {
				status = http.StatusInternalServerError
			}
1373
			if errorMsg, ok := r["error"].(string); ok {
Josh's avatar
Josh committed
1374
				c.JSON(status, gin.H{"error": errorMsg})
1375
1376
				return
			} else {
Josh's avatar
Josh committed
1377
				c.JSON(status, gin.H{"error": "unexpected error format in progress response"})
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
				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
1388
func streamResponse(c *gin.Context, ch chan any) {
1389
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
1390
1391
1392
1393
1394
1395
1396
1397
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

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

1402
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
1403
1404
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
1405
			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1406
1407
1408
1409
1410
1411
			return false
		}

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

1413
func (s *Server) PsHandler(c *gin.Context) {
1414
	models := []api.ProcessModelResponse{}
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425

	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,
		}

1426
		mr := api.ProcessModelResponse{
1427
1428
1429
1430
1431
1432
1433
1434
			Model:     model.ShortName,
			Name:      model.ShortName,
			Size:      int64(v.estimatedTotal),
			SizeVRAM:  int64(v.estimatedVRAM),
			Digest:    model.Digest,
			Details:   modelDetails,
			ExpiresAt: v.expiresAt,
		}
1435
1436
1437
1438
1439
1440
1441
1442
		// 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)
		}

1443
1444
1445
		models = append(models, mr)
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1446
1447
1448
1449
1450
	slices.SortStableFunc(models, func(i, j api.ProcessModelResponse) int {
		// longest duration remaining listed first
		return cmp.Compare(j.ExpiresAt.Unix(), i.ExpiresAt.Unix())
	})

1451
	c.JSON(http.StatusOK, api.ProcessResponse{Models: models})
1452
1453
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1454
func (s *Server) ChatHandler(c *gin.Context) {
1455
1456
	checkpointStart := time.Now()

Bruce MacDonald's avatar
Bruce MacDonald committed
1457
	var req api.ChatRequest
Michael Yang's avatar
Michael Yang committed
1458
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1459
1460
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
1461
	} else if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1462
1463
1464
1465
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Patrick Devine's avatar
Patrick Devine committed
1466
1467
1468
1469
1470
1471
1472
	// expire the runner
	if len(req.Messages) == 0 && req.KeepAlive != nil && int(req.KeepAlive.Seconds()) == 0 {
		model, err := GetModel(req.Model)
		if err != nil {
			switch {
			case os.IsNotExist(err):
				c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
1473
			case err.Error() == errtypes.InvalidModelNameErrMsg:
Patrick Devine's avatar
Patrick Devine committed
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
				c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			default:
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			}
			return
		}
		s.sched.expireRunner(model)

		c.JSON(http.StatusOK, api.ChatResponse{
			Model:      req.Model,
			CreatedAt:  time.Now().UTC(),
			Message:    api.Message{Role: "assistant"},
			Done:       true,
			DoneReason: "unload",
		})
		return
	}

Michael Yang's avatar
Michael Yang committed
1492
	caps := []Capability{CapabilityCompletion}
1493
	if len(req.Tools) > 0 {
Michael Yang's avatar
tools  
Michael Yang committed
1494
1495
1496
		caps = append(caps, CapabilityTools)
	}

1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
	name := model.ParseName(req.Model)
	if !name.IsValid() {
		c.JSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
	}
	name, err := getExistingName(name)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
	}

	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), caps, req.Options, req.KeepAlive)
Michael Yang's avatar
Michael Yang committed
1509
1510
	if errors.Is(err, errCapabilityCompletion) {
		c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("%q does not support chat", req.Model)})
Bruce MacDonald's avatar
Bruce MacDonald committed
1511
		return
Michael Yang's avatar
Michael Yang committed
1512
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
1513
		handleScheduleError(c, req.Model, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
1514
1515
		return
	}
Michael Yang's avatar
Michael Yang committed
1516

1517
1518
	checkpointLoaded := time.Now()

Michael Yang's avatar
Michael Yang committed
1519
1520
	if len(req.Messages) == 0 {
		c.JSON(http.StatusOK, api.ChatResponse{
1521
			Model:      req.Model,
Michael Yang's avatar
Michael Yang committed
1522
1523
			CreatedAt:  time.Now().UTC(),
			Message:    api.Message{Role: "assistant"},
1524
1525
			Done:       true,
			DoneReason: "load",
Michael Yang's avatar
Michael Yang committed
1526
		})
1527
1528
1529
		return
	}

Michael Yang's avatar
Michael Yang committed
1530
	msgs := append(m.Messages, req.Messages...)
1531
	if req.Messages[0].Role != "system" && m.System != "" {
Michael Yang's avatar
Michael Yang committed
1532
		msgs = append([]api.Message{{Role: "system", Content: m.System}}, msgs...)
1533
1534
	}

Michael Yang's avatar
Michael Yang committed
1535
	prompt, images, err := chatPrompt(c.Request.Context(), m, r.Tokenize, opts, msgs, req.Tools)
Michael Yang's avatar
Michael Yang committed
1536
	if err != nil {
1537
		slog.Error("chat prompt error", "error", err)
Michael Yang's avatar
Michael Yang committed
1538
1539
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
1540
1541
	}

Michael Yang's avatar
Michael Yang committed
1542
	slog.Debug("chat request", "images", len(images), "prompt", prompt)
1543

Bruce MacDonald's avatar
Bruce MacDonald committed
1544
1545
1546
	ch := make(chan any)
	go func() {
		defer close(ch)
1547
		var sb strings.Builder
1548
		var toolCallIndex int = 0
Michael Yang's avatar
Michael Yang committed
1549
		if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
Michael Yang's avatar
Michael Yang committed
1550
1551
1552
			Prompt:  prompt,
			Images:  images,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
1553
			Options: opts,
Michael Yang's avatar
Michael Yang committed
1554
		}, func(r llm.CompletionResponse) {
1555
			res := api.ChatResponse{
1556
1557
1558
1559
1560
				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
1561
1562
1563
1564
1565
1566
1567
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}
1568
1569
1570
1571
1572
1573

			if r.Done {
				res.TotalDuration = time.Since(checkpointStart)
				res.LoadDuration = checkpointLoaded.Sub(checkpointStart)
			}

1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
			// TODO: tool call checking and filtering should be moved outside of this callback once streaming
			// however this was a simple change for now without reworking streaming logic of this (and other)
			// handlers
			if req.Stream != nil && !*req.Stream || len(req.Tools) == 0 {
				ch <- res
				return
			}

			// Streaming tool calls:
			// If tools are recognized, use a flag to track the sending of a tool downstream
			// This ensures that content is cleared from the message on the last chunk sent
			sb.WriteString(r.Content)
			if toolCalls, ok := m.parseToolCalls(sb.String()); ok {
				res.Message.ToolCalls = toolCalls
1588
1589
1590
1591
				for i := range toolCalls {
					toolCalls[i].Function.Index = toolCallIndex
					toolCallIndex++
				}
1592
1593
1594
1595
1596
1597
1598
1599
				res.Message.Content = ""
				sb.Reset()
				ch <- res
				return
			}

			if r.Done {
				// Send any remaining content if no tool calls were detected
1600
				if toolCallIndex == 0 {
1601
1602
1603
1604
					res.Message.Content = sb.String()
				}
				ch <- res
			}
Michael Yang's avatar
Michael Yang committed
1605
		}); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1606
1607
1608
1609
1610
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
Michael Yang's avatar
tools  
Michael Yang committed
1611
		var resp api.ChatResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
1612
		var sb strings.Builder
Michael Yang's avatar
Michael Yang committed
1613
1614
		for rr := range ch {
			switch t := rr.(type) {
1615
			case api.ChatResponse:
Michael Yang's avatar
Michael Yang committed
1616
				sb.WriteString(t.Message.Content)
Michael Yang's avatar
tools  
Michael Yang committed
1617
				resp = t
1618
			case gin.H:
Michael Yang's avatar
Michael Yang committed
1619
1620
1621
				msg, ok := t["error"].(string)
				if !ok {
					msg = "unexpected error format in response"
1622
				}
Michael Yang's avatar
Michael Yang committed
1623
1624
1625

				c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
				return
1626
			default:
Michael Yang's avatar
Michael Yang committed
1627
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
1628
				return
Bruce MacDonald's avatar
Bruce MacDonald committed
1629
1630
			}
		}
1631

Michael Yang's avatar
tools  
Michael Yang committed
1632
		resp.Message.Content = sb.String()
1633
1634
1635
1636
1637
1638

		if len(req.Tools) > 0 {
			if toolCalls, ok := m.parseToolCalls(sb.String()); ok {
				resp.Message.ToolCalls = toolCalls
				resp.Message.Content = ""
			}
Michael Yang's avatar
tools  
Michael Yang committed
1639
1640
1641
		}

		c.JSON(http.StatusOK, resp)
Bruce MacDonald's avatar
Bruce MacDonald committed
1642
1643
1644
1645
1646
		return
	}

	streamResponse(c, ch)
}
1647

Michael Yang's avatar
Michael Yang committed
1648
func handleScheduleError(c *gin.Context, name string, err error) {
Michael Yang's avatar
Michael Yang committed
1649
	switch {
1650
	case errors.Is(err, errCapabilities), errors.Is(err, errRequired):
Michael Yang's avatar
Michael Yang committed
1651
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
1652
	case errors.Is(err, context.Canceled):
1653
		c.JSON(499, gin.H{"error": "request canceled"})
Michael Yang's avatar
Michael Yang committed
1654
	case errors.Is(err, ErrMaxQueue):
1655
		c.JSON(http.StatusServiceUnavailable, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
1656
1657
	case errors.Is(err, os.ErrNotExist):
		c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model %q not found, try pulling it first", name)})
Michael Yang's avatar
Michael Yang committed
1658
1659
	default:
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
1660
1661
	}
}