routes.go 40.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
	"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"
Michael Yang's avatar
Michael Yang committed
33
	"github.com/ollama/ollama/fs/ggml"
34
	"github.com/ollama/ollama/llm"
35
	"github.com/ollama/ollama/model/models/mllama"
36
	"github.com/ollama/ollama/openai"
Michael Yang's avatar
Michael Yang committed
37
	"github.com/ollama/ollama/template"
38
	"github.com/ollama/ollama/types/errtypes"
Michael Yang's avatar
Michael Yang committed
39
	"github.com/ollama/ollama/types/model"
40
	"github.com/ollama/ollama/version"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
41
42
)

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

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

Michael Yang's avatar
Michael Yang committed
50
51
52
53
54
55
56
57
58
59
60
61
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
62
63
64
65
var (
	errRequired    = errors.New("is required")
	errBadTemplate = errors.New("template error")
)
Michael Yang's avatar
Michael Yang committed
66

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

Michael Yang's avatar
Michael Yang committed
80
81
82
// 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
83
	if name == "" {
Michael Yang's avatar
Michael Yang committed
84
		return nil, nil, nil, fmt.Errorf("model %w", errRequired)
Bruce MacDonald's avatar
Bruce MacDonald committed
85
86
	}

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

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

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

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

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

func (s *Server) GenerateHandler(c *gin.Context) {
113
	checkpointStart := time.Now()
Michael Yang's avatar
Michael Yang committed
114
115
116
117
118
119
	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
120
121
122
		return
	}

123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
	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())
140
141
	if err != nil {
		switch {
142
		case errors.Is(err, fs.ErrNotExist):
143
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
144
		case err.Error() == errtypes.InvalidModelNameErrMsg:
145
146
147
148
149
150
151
			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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
	// 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
	}

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

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

176
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), caps, req.Options, req.KeepAlive)
Michael Yang's avatar
Michael Yang committed
177
178
179
180
	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
181
182
183
184
		handleScheduleError(c, req.Model, err)
		return
	}

185
186
	checkpointLoaded := time.Now()

187
	// load the model
Michael Yang's avatar
Michael Yang committed
188
189
190
191
192
193
194
	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
195
196
		return
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
197

198
199
200
201
202
203
	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
204
205
	images := make([]llm.ImageData, len(req.Images))
	for i := range req.Images {
Jesse Gross's avatar
Jesse Gross committed
206
		if isMllama && !envconfig.NewEngine() {
207
			data, opts, err := mllama.Preprocess(bytes.NewReader(req.Images[i]))
208
209
210
211
212
			if err != nil {
				c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "error processing image"})
				return
			}

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

219
220
221
222
223
224
225
			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
			}

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

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

243
244
245
246
247
248
249
250
251
252
253
254
		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
255
256
257
258
			if req.Context == nil {
				msgs = append(msgs, m.Messages...)
			}

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

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

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

		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
287
288
	}

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

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

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

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

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

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

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

	streamResponse(c, ch)
}

370
func (s *Server) EmbedHandler(c *gin.Context) {
371
	checkpointStart := time.Now()
372
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
	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:
405
406
407
408
		if req.Input != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid input type"})
			return
		}
409
410
	}

411
412
413
414
415
416
417
	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)
418
419
420
421
422
	if err != nil {
		handleScheduleError(c, req.Model, err)
		return
	}

423
424
	checkpointLoaded := time.Now()

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

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

436
	var count int
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
	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
			}
		}

459
460
		count += len(tokens)

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

	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
		})
475
476
	}

477
478
479
480
	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
481
482
483
	}

	resp := api.EmbedResponse{
484
		Model:           req.Model,
485
		Embeddings:      embeddings,
486
487
		TotalDuration:   time.Since(checkpointStart),
		LoadDuration:    checkpointLoaded.Sub(checkpointStart),
488
		PromptEvalCount: count,
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
	}
	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
510
func (s *Server) EmbeddingsHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
511
	var req api.EmbeddingRequest
Michael Yang's avatar
Michael Yang committed
512
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
Bruce MacDonald's avatar
Bruce MacDonald 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 {
Bruce MacDonald's avatar
Bruce MacDonald committed
516
517
518
519
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

520
521
522
523
524
525
526
	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
527
	if err != nil {
Michael Yang's avatar
Michael Yang committed
528
		handleScheduleError(c, req.Model, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
529
530
531
		return
	}

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

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

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

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

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

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

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

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

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

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

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

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

604
605
606
	streamResponse(c, ch)
}

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

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

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

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

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

643
644
645
646
647
648
649
		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
650
			ch <- gin.H{"error": err.Error()}
651
652
653
		}
	}()

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

659
660
661
	streamResponse(c, ch)
}

662
663
664
665
// 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.
666
667
668
func getExistingName(n model.Name) (model.Name, error) {
	var zero model.Name
	existing, err := Manifests(true)
669
	if err != nil {
670
		return zero, err
671
	}
672
	var set model.Name // tracks parts already canonicalized
673
	for e := range existing {
674
675
676
677
678
679
680
681
682
683
684
		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
685
686
		}
	}
687
	return n, nil
688
689
}

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

700
701
702
	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))})
703
704
		return
	}
Michael Yang's avatar
Michael Yang committed
705

706
707
708
709
710
711
	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
	}

712
	m, err := ParseNamedManifest(n)
Michael Yang's avatar
Michael Yang committed
713
	if err != nil {
714
715
716
717
718
719
		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
720
721
722
		return
	}

723
	if err := m.Remove(); err != nil {
Michael Yang's avatar
Michael Yang committed
724
725
726
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
727
728
729
730
731

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

734
func (s *Server) ShowHandler(c *gin.Context) {
Patrick Devine's avatar
Patrick Devine committed
735
	var req api.ShowRequest
Michael Yang's avatar
Michael Yang committed
736
737
738
739
740
741
742
	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
743
744
745
		return
	}

Michael Yang's avatar
Michael Yang committed
746
	if req.Model != "" {
Michael Yang's avatar
Michael Yang committed
747
		// noop
Michael Yang's avatar
Michael Yang committed
748
	} else if req.Name != "" {
Michael Yang's avatar
Michael Yang committed
749
		req.Model = req.Name
Michael Yang's avatar
Michael Yang committed
750
	} else {
751
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
752
753
754
		return
	}

755
	resp, err := GetModelInfo(req)
Patrick Devine's avatar
Patrick Devine committed
756
	if err != nil {
757
758
		switch {
		case os.IsNotExist(err):
Michael Yang's avatar
Michael Yang committed
759
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
760
		case err.Error() == errtypes.InvalidModelNameErrMsg:
761
762
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
Patrick Devine's avatar
Patrick Devine committed
763
764
765
766
767
768
769
770
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

	c.JSON(http.StatusOK, resp)
}

771
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
772
773
774
775
776
777
778
779
780
781
	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
782
783
784
785
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
786
	modelDetails := api.ModelDetails{
787
788
789
790
791
792
		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
793
794
	}

795
	if req.System != "" {
796
		m.System = req.System
797
798
	}

Michael Yang's avatar
Michael Yang committed
799
800
801
	msgs := make([]api.Message, len(m.Messages))
	for i, msg := range m.Messages {
		msgs[i] = api.Message{Role: msg.Role, Content: msg.Content}
802
803
	}

804
	manifest, err := ParseNamedManifest(name)
805
806
807
808
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
809
	resp := &api.ShowResponse{
810
811
		License:    strings.Join(m.License, "\n"),
		System:     m.System,
Michael Yang's avatar
Michael Yang committed
812
		Template:   m.Template.String(),
813
814
815
		Details:    modelDetails,
		Messages:   msgs,
		ModifiedAt: manifest.fi.ModTime(),
Patrick Devine's avatar
Patrick Devine committed
816
817
818
819
	}

	var params []string
	cs := 30
820
	for k, v := range m.Options {
Patrick Devine's avatar
Patrick Devine committed
821
822
823
		switch val := v.(type) {
		case []interface{}:
			for _, nv := range val {
Patrick Devine's avatar
Patrick Devine committed
824
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
Patrick Devine's avatar
Patrick Devine committed
825
			}
Patrick Devine's avatar
Patrick Devine committed
826
827
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
Patrick Devine's avatar
Patrick Devine committed
828
829
830
831
		}
	}
	resp.Parameters = strings.Join(params, "\n")

832
833
	for k, v := range req.Options {
		if _, ok := req.Options[k]; ok {
834
			m.Options[k] = v
835
836
837
		}
	}

838
	var sb strings.Builder
839
	fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"")
840
	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
841
842
	fmt.Fprintf(&sb, "# FROM %s\n\n", m.ShortName)
	fmt.Fprint(&sb, m.String())
843
	resp.Modelfile = sb.String()
844

845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
	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
861
862
863
	return resp, nil
}

Michael Yang's avatar
Michael Yang committed
864
func getKVData(digest string, verbose bool) (ggml.KV, error) {
865
866
867
868
869
	maxArraySize := 0
	if verbose {
		maxArraySize = -1
	}
	kvData, err := llm.LoadModel(digest, maxArraySize)
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
	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
}

887
func (s *Server) ListHandler(c *gin.Context) {
888
	ms, err := Manifests(true)
Patrick Devine's avatar
Patrick Devine committed
889
890
891
892
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
893

894
	models := []api.ListModelResponse{}
895
896
	for n, m := range ms {
		var cf ConfigV2
897
898
899
900
901
902
903
904
905
906
907
908
909

		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
910
		}
Michael Yang's avatar
Michael Yang committed
911

912
		// tag should never be masked
913
		models = append(models, api.ListModelResponse{
914
915
916
917
918
919
920
921
922
923
924
925
926
			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
927
928
	}

929
	slices.SortStableFunc(models, func(i, j api.ListModelResponse) int {
930
931
932
933
		// most recently modified first
		return cmp.Compare(j.ModifiedAt.Unix(), i.ModifiedAt.Unix())
	})

Michael Yang's avatar
Michael Yang committed
934
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
935
936
}

937
func (s *Server) CopyHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
938
939
	var r api.CopyRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
940
941
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
942
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
943
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Patrick Devine's avatar
Patrick Devine committed
944
945
946
		return
	}

Michael Yang's avatar
Michael Yang committed
947
948
	src := model.ParseName(r.Source)
	if !src.IsValid() {
Michael Yang's avatar
Michael Yang committed
949
950
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("source %q is invalid", r.Source)})
		return
951
	}
952
953
954
955
956
	src, err := getExistingName(src)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
957

Michael Yang's avatar
Michael Yang committed
958
959
	dst := model.ParseName(r.Destination)
	if !dst.IsValid() {
960
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("destination %q is invalid", r.Destination)})
Patrick Devine's avatar
Patrick Devine committed
961
962
		return
	}
963
964
	dst, err = getExistingName(dst)
	if err != nil {
965
966
967
968
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
969
970
971
972
973
	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
974
975
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
976
func (s *Server) HeadBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
977
978
979
980
981
982
983
984
985
986
987
	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
988
	c.Status(http.StatusOK)
Michael Yang's avatar
Michael Yang committed
989
990
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
991
func (s *Server) CreateBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
992
993
	if ib, ok := intermediateBlobs[c.Param("digest")]; ok {
		p, err := GetBlobsPath(ib)
994
995
996
997
998
999
		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
1000
1001
			slog.Info("evicting intermediate blob which no longer exists", "digest", ib)
			delete(intermediateBlobs, c.Param("digest"))
1002
1003
1004
1005
1006
1007
1008
1009
1010
		} else if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		} else {
			c.Status(http.StatusOK)
			return
		}
	}

1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
	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
	}

1029
	layer, err := NewLayer(c.Request.Body, "")
Michael Yang's avatar
Michael Yang committed
1030
1031
1032
1033
1034
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

1035
1036
	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
1037
1038
1039
		return
	}

Michael Yang's avatar
Michael Yang committed
1040
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
1041
1042
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
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
}

1064
func allowedHost(host string) bool {
1065
1066
	host = strings.ToLower(host)

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1067
	if host == "" || host == "localhost" {
1068
1069
1070
		return true
	}

1071
	if hostname, err := os.Hostname(); err == nil && host == strings.ToLower(hostname) {
1072
1073
1074
		return true
	}

Michael Yang's avatar
lint  
Michael Yang committed
1075
	tlds := []string{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1076
1077
1078
		"localhost",
		"local",
		"internal",
1079
	}
1080

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1081
	// check if the host is a local TLD
1082
1083
1084
1085
1086
1087
	for _, tld := range tlds {
		if strings.HasSuffix(host, "."+tld) {
			return true
		}
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1088
	return false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1089
}
1090

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1091
1092
1093
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
	return func(c *gin.Context) {
		if addr == nil {
1094
1095
1096
1097
			c.Next()
			return
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1098
		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
1099
1100
1101
1102
1103
1104
1105
1106
1107
			c.Next()
			return
		}

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1108
		if addr, err := netip.ParseAddr(host); err == nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1109
			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1110
1111
1112
1113
1114
				c.Next()
				return
			}
		}

1115
		if allowedHost(host) {
Michael Yang's avatar
lint  
Michael Yang committed
1116
			if c.Request.Method == http.MethodOptions {
1117
1118
1119
1120
				c.AbortWithStatus(http.StatusNoContent)
				return
			}

1121
1122
1123
1124
1125
1126
			c.Next()
			return
		}

		c.AbortWithStatus(http.StatusForbidden)
	}
1127
}
1128

1129
func (s *Server) GenerateRoutes() http.Handler {
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
	corsConfig := cors.DefaultConfig()
	corsConfig.AllowWildcard = true
	corsConfig.AllowBrowserExtensions = true
	corsConfig.AllowHeaders = []string{
		"Authorization",
		"Content-Type",
		"User-Agent",
		"Accept",
		"X-Requested-With",

		// OpenAI compatibility headers
		"x-stainless-lang",
		"x-stainless-package-version",
		"x-stainless-os",
		"x-stainless-arch",
		"x-stainless-retry-count",
		"x-stainless-runtime",
		"x-stainless-runtime-version",
		"x-stainless-async",
		"x-stainless-helper-method",
		"x-stainless-poll-helper",
		"x-stainless-custom-poll-interval",
		"x-stainless-timeout",
	}
	corsConfig.AllowOrigins = envconfig.AllowedOrigins()
Michael Yang's avatar
Michael Yang committed
1155

Bruce MacDonald's avatar
Bruce MacDonald committed
1156
	r := gin.Default()
1157
	r.Use(
1158
		cors.New(corsConfig),
1159
		allowedHostsMiddleware(s.addr),
1160
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
1161

1162
1163
1164
1165
1166
1167
1168
	// General
	r.HEAD("/", func(c *gin.Context) { c.String(http.StatusOK, "Ollama is running") })
	r.GET("/", func(c *gin.Context) { c.String(http.StatusOK, "Ollama is running") })
	r.HEAD("/api/version", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"version": version.Version}) })
	r.GET("/api/version", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"version": version.Version}) })

	// Local model cache management
1169
1170
1171
	r.POST("/api/pull", s.PullHandler)
	r.POST("/api/push", s.PushHandler)
	r.DELETE("/api/delete", s.DeleteHandler)
1172
1173
	r.HEAD("/api/tags", s.ListHandler)
	r.GET("/api/tags", s.ListHandler)
1174
	r.POST("/api/show", s.ShowHandler)
1175
1176
1177

	// Create
	r.POST("/api/create", s.CreateHandler)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1178
1179
	r.POST("/api/blobs/:digest", s.CreateBlobHandler)
	r.HEAD("/api/blobs/:digest", s.HeadBlobHandler)
1180
1181
1182
	r.POST("/api/copy", s.CopyHandler)

	// Inference
1183
	r.GET("/api/ps", s.PsHandler)
1184
1185
1186
1187
	r.POST("/api/generate", s.GenerateHandler)
	r.POST("/api/chat", s.ChatHandler)
	r.POST("/api/embed", s.EmbedHandler)
	r.POST("/api/embeddings", s.EmbeddingsHandler)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1188

1189
	// Inference (OpenAI compatibility)
1190
	r.POST("/v1/chat/completions", openai.ChatMiddleware(), s.ChatHandler)
1191
	r.POST("/v1/completions", openai.CompletionsMiddleware(), s.GenerateHandler)
1192
	r.POST("/v1/embeddings", openai.EmbeddingsMiddleware(), s.EmbedHandler)
1193
1194
	r.GET("/v1/models", openai.ListMiddleware(), s.ListHandler)
	r.GET("/v1/models/:model", openai.RetrieveMiddleware(), s.ShowHandler)
1195

1196
1197
1198
1199
	return r
}

func Serve(ln net.Listener) error {
Michael Yang's avatar
Michael Yang committed
1200
	level := slog.LevelInfo
Michael Yang's avatar
Michael Yang committed
1201
	if envconfig.Debug() {
Michael Yang's avatar
Michael Yang committed
1202
		level = slog.LevelDebug
1203
	}
Michael Yang's avatar
Michael Yang committed
1204

1205
	slog.Info("server config", "env", envconfig.Values())
Michael Yang's avatar
Michael Yang committed
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
	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))

1221
1222
1223
1224
1225
1226
1227
1228
	blobsDir, err := GetBlobsPath("")
	if err != nil {
		return err
	}
	if err := fixBlobs(blobsDir); err != nil {
		return err
	}

Michael Yang's avatar
bool  
Michael Yang committed
1229
	if !envconfig.NoPrune() {
1230
1231
1232
1233
1234
1235
1236
		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
			}
1237

1238
1239
1240
1241
			manifestsPath, err := GetManifestPath()
			if err != nil {
				return err
			}
1242

1243
1244
1245
			if err := PruneDirectory(manifestsPath); err != nil {
				return err
			}
1246
1247
1248
		}
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1249
	ctx, done := context.WithCancel(context.Background())
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1250
1251
	schedCtx, schedDone := context.WithCancel(ctx)
	sched := InitScheduler(schedCtx)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1252
	s := &Server{addr: ln.Addr(), sched: sched}
1253
1254

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

1256
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1257
	srvr := &http.Server{
1258
1259
1260
1261
1262
1263
1264
1265
1266
		// 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
1267
1268
	}

1269
1270
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
1271
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
1272
1273
	go func() {
		<-signals
1274
		srvr.Close()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1275
		schedDone()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1276
		sched.unloadAllRunners()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1277
		done()
1278
1279
	}()

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1280
	s.sched.Run(schedCtx)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1281
1282
1283

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

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1287
1288
1289
1290
1291
1292
1293
	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()
1294
	return nil
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1295
}
Michael Yang's avatar
Michael Yang committed
1296

1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
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
1307
1308
1309
1310
			status, ok := r["status"].(int)
			if !ok {
				status = http.StatusInternalServerError
			}
1311
			if errorMsg, ok := r["error"].(string); ok {
Josh's avatar
Josh committed
1312
				c.JSON(status, gin.H{"error": errorMsg})
1313
1314
				return
			} else {
Josh's avatar
Josh committed
1315
				c.JSON(status, gin.H{"error": "unexpected error format in progress response"})
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
				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
1326
func streamResponse(c *gin.Context, ch chan any) {
1327
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
1328
1329
1330
1331
1332
1333
1334
1335
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

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

1340
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
1341
1342
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
1343
			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1344
1345
1346
1347
1348
1349
			return false
		}

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

1351
func (s *Server) PsHandler(c *gin.Context) {
1352
	models := []api.ProcessModelResponse{}
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363

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

1364
		mr := api.ProcessModelResponse{
1365
1366
1367
1368
1369
1370
1371
1372
			Model:     model.ShortName,
			Name:      model.ShortName,
			Size:      int64(v.estimatedTotal),
			SizeVRAM:  int64(v.estimatedVRAM),
			Digest:    model.Digest,
			Details:   modelDetails,
			ExpiresAt: v.expiresAt,
		}
1373
1374
1375
1376
1377
1378
1379
1380
		// 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)
		}

1381
1382
1383
		models = append(models, mr)
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1384
1385
1386
1387
1388
	slices.SortStableFunc(models, func(i, j api.ProcessModelResponse) int {
		// longest duration remaining listed first
		return cmp.Compare(j.ExpiresAt.Unix(), i.ExpiresAt.Unix())
	})

1389
	c.JSON(http.StatusOK, api.ProcessResponse{Models: models})
1390
1391
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1392
func (s *Server) ChatHandler(c *gin.Context) {
1393
1394
	checkpointStart := time.Now()

Bruce MacDonald's avatar
Bruce MacDonald committed
1395
	var req api.ChatRequest
Michael Yang's avatar
Michael Yang committed
1396
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1397
1398
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
1399
	} else if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1400
1401
1402
1403
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Patrick Devine's avatar
Patrick Devine committed
1404
1405
1406
1407
1408
1409
1410
	// 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)})
1411
			case err.Error() == errtypes.InvalidModelNameErrMsg:
Patrick Devine's avatar
Patrick Devine committed
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
				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
1430
	caps := []Capability{CapabilityCompletion}
1431
	if len(req.Tools) > 0 {
Michael Yang's avatar
tools  
Michael Yang committed
1432
1433
1434
		caps = append(caps, CapabilityTools)
	}

1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
	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
1447
1448
	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
1449
		return
Michael Yang's avatar
Michael Yang committed
1450
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
1451
		handleScheduleError(c, req.Model, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
1452
1453
		return
	}
Michael Yang's avatar
Michael Yang committed
1454

1455
1456
	checkpointLoaded := time.Now()

Michael Yang's avatar
Michael Yang committed
1457
1458
	if len(req.Messages) == 0 {
		c.JSON(http.StatusOK, api.ChatResponse{
1459
			Model:      req.Model,
Michael Yang's avatar
Michael Yang committed
1460
1461
			CreatedAt:  time.Now().UTC(),
			Message:    api.Message{Role: "assistant"},
1462
1463
			Done:       true,
			DoneReason: "load",
Michael Yang's avatar
Michael Yang committed
1464
		})
1465
1466
1467
		return
	}

Michael Yang's avatar
Michael Yang committed
1468
	msgs := append(m.Messages, req.Messages...)
1469
	if req.Messages[0].Role != "system" && m.System != "" {
Michael Yang's avatar
Michael Yang committed
1470
		msgs = append([]api.Message{{Role: "system", Content: m.System}}, msgs...)
1471
1472
	}

Michael Yang's avatar
Michael Yang committed
1473
	prompt, images, err := chatPrompt(c.Request.Context(), m, r.Tokenize, opts, msgs, req.Tools)
Michael Yang's avatar
Michael Yang committed
1474
	if err != nil {
1475
		slog.Error("chat prompt error", "error", err)
Michael Yang's avatar
Michael Yang committed
1476
1477
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
1478
1479
	}

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

Bruce MacDonald's avatar
Bruce MacDonald committed
1482
1483
1484
	ch := make(chan any)
	go func() {
		defer close(ch)
1485
		var sb strings.Builder
1486
		var toolCallIndex int = 0
Michael Yang's avatar
Michael Yang committed
1487
		if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
Michael Yang's avatar
Michael Yang committed
1488
1489
1490
			Prompt:  prompt,
			Images:  images,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
1491
			Options: opts,
Michael Yang's avatar
Michael Yang committed
1492
		}, func(r llm.CompletionResponse) {
1493
			res := api.ChatResponse{
1494
1495
1496
1497
1498
				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
1499
1500
1501
1502
1503
1504
1505
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}
1506
1507
1508
1509
1510
1511

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

1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
			// 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
1526
1527
1528
1529
				for i := range toolCalls {
					toolCalls[i].Function.Index = toolCallIndex
					toolCallIndex++
				}
1530
1531
1532
1533
1534
1535
1536
1537
				res.Message.Content = ""
				sb.Reset()
				ch <- res
				return
			}

			if r.Done {
				// Send any remaining content if no tool calls were detected
1538
				if toolCallIndex == 0 {
1539
1540
1541
1542
					res.Message.Content = sb.String()
				}
				ch <- res
			}
Michael Yang's avatar
Michael Yang committed
1543
		}); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1544
1545
1546
1547
1548
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
Michael Yang's avatar
tools  
Michael Yang committed
1549
		var resp api.ChatResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
1550
		var sb strings.Builder
Michael Yang's avatar
Michael Yang committed
1551
1552
		for rr := range ch {
			switch t := rr.(type) {
1553
			case api.ChatResponse:
Michael Yang's avatar
Michael Yang committed
1554
				sb.WriteString(t.Message.Content)
Michael Yang's avatar
tools  
Michael Yang committed
1555
				resp = t
1556
			case gin.H:
Michael Yang's avatar
Michael Yang committed
1557
1558
1559
				msg, ok := t["error"].(string)
				if !ok {
					msg = "unexpected error format in response"
1560
				}
Michael Yang's avatar
Michael Yang committed
1561
1562
1563

				c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
				return
1564
			default:
Michael Yang's avatar
Michael Yang committed
1565
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
1566
				return
Bruce MacDonald's avatar
Bruce MacDonald committed
1567
1568
			}
		}
1569

Michael Yang's avatar
tools  
Michael Yang committed
1570
		resp.Message.Content = sb.String()
1571
1572
1573
1574
1575
1576

		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
1577
1578
1579
		}

		c.JSON(http.StatusOK, resp)
Bruce MacDonald's avatar
Bruce MacDonald committed
1580
1581
1582
1583
1584
		return
	}

	streamResponse(c, ch)
}
1585

Michael Yang's avatar
Michael Yang committed
1586
func handleScheduleError(c *gin.Context, name string, err error) {
Michael Yang's avatar
Michael Yang committed
1587
	switch {
1588
	case errors.Is(err, errCapabilities), errors.Is(err, errRequired):
Michael Yang's avatar
Michael Yang committed
1589
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
1590
	case errors.Is(err, context.Canceled):
1591
		c.JSON(499, gin.H{"error": "request canceled"})
Michael Yang's avatar
Michael Yang committed
1592
	case errors.Is(err, ErrMaxQueue):
1593
		c.JSON(http.StatusServiceUnavailable, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
1594
1595
	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
1596
1597
	default:
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
1598
1599
	}
}