routes.go 39.8 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
	"log/slog"
13
	"math"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
14
15
	"net"
	"net/http"
16
	"net/netip"
17
	"os"
18
	"os/signal"
Michael Yang's avatar
Michael Yang committed
19
	"path/filepath"
20
	"slices"
Michael Yang's avatar
Michael Yang committed
21
	"strings"
22
	"syscall"
23
	"time"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
24

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

29
	"github.com/ollama/ollama/api"
30
	"github.com/ollama/ollama/build"
31
	"github.com/ollama/ollama/discover"
32
	"github.com/ollama/ollama/envconfig"
33
34
	"github.com/ollama/ollama/llm"
	"github.com/ollama/ollama/openai"
35
	"github.com/ollama/ollama/parser"
36
	"github.com/ollama/ollama/runners"
37
	"github.com/ollama/ollama/server/imageproc"
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
	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)})
		case err.Error() == "invalid model name":
			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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
	// 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
	}

Michael Yang's avatar
Michael Yang committed
151
152
153
154
155
	if req.Format != "" && req.Format != "json" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be empty or \"json\""})
		return
	} else if req.Raw && (req.Template != "" || req.System != "" || len(req.Context) > 0) {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "raw mode does not support template, system, or context"})
Michael Yang's avatar
Michael Yang committed
156
157
158
		return
	}

Michael Yang's avatar
Michael Yang committed
159
	caps := []Capability{CapabilityCompletion}
160
161
162
163
	if req.Suffix != "" {
		caps = append(caps, CapabilityInsert)
	}

Michael Yang's avatar
Michael Yang committed
164
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), req.Model, caps, req.Options, req.KeepAlive)
Michael Yang's avatar
Michael Yang committed
165
166
167
168
	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
169
170
171
172
		handleScheduleError(c, req.Model, err)
		return
	}

173
174
	checkpointLoaded := time.Now()

175
	// load the model
Michael Yang's avatar
Michael Yang committed
176
177
178
179
180
181
182
	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
183
184
		return
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
185

186
187
188
189
190
191
	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
192
193
	images := make([]llm.ImageData, len(req.Images))
	for i := range req.Images {
194
195
196
197
198
199
200
201
202
203
204
205
206
207
		if isMllama {
			data, aspectRatioID, err := imageproc.Preprocess(req.Images[i])
			if err != nil {
				c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "error processing image"})
				return
			}

			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
			}

208
			images[i] = llm.ImageData{ID: i, Data: buf.Bytes(), AspectRatioID: aspectRatioID}
209
210
211
		} else {
			images[i] = llm.ImageData{ID: i, Data: req.Images[i]}
		}
Michael Yang's avatar
Michael Yang committed
212
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
213

Michael Yang's avatar
Michael Yang committed
214
215
	prompt := req.Prompt
	if !req.Raw {
Michael Yang's avatar
Michael Yang committed
216
		tmpl := m.Template
Michael Yang's avatar
Michael Yang committed
217
218
219
220
221
222
223
224
		if req.Template != "" {
			tmpl, err = template.Parse(req.Template)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}

225
226
227
228
229
230
231
232
233
234
235
236
		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
237
238
239
240
			if req.Context == nil {
				msgs = append(msgs, m.Messages...)
			}

241
			for _, i := range images {
242
				imgPrompt := ""
243
				if isMllama {
244
					imgPrompt = "<|image|>"
245
				}
246
				msgs = append(msgs, api.Message{Role: "user", Content: fmt.Sprintf("[img-%d]"+imgPrompt, i.ID)})
247
248
249
250
251
			}

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

Michael Yang's avatar
Michael Yang committed
252
253
		var b bytes.Buffer
		if req.Context != nil {
254
			slog.Warn("the context field is deprecated and will be removed in a future version of Ollama")
255
			s, err := r.Detokenize(c.Request.Context(), req.Context)
Michael Yang's avatar
Michael Yang committed
256
257
258
259
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
260
			b.WriteString(s)
Michael Yang's avatar
Michael Yang committed
261
		}
262
263
264
265
266
267
268

		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
269
270
	}

271
	slog.Debug("generate request", "images", len(images), "prompt", prompt)
272

Bruce MacDonald's avatar
Bruce MacDonald committed
273
274
	ch := make(chan any)
	go func() {
275
276
		// TODO (jmorganca): avoid building the response twice both here and below
		var sb strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
277
		defer close(ch)
Michael Yang's avatar
Michael Yang committed
278
		if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
Michael Yang's avatar
Michael Yang committed
279
280
			Prompt:  prompt,
			Images:  images,
281
			Format:  json.RawMessage(req.Format),
Michael Yang's avatar
Michael Yang committed
282
			Options: opts,
283
284
		}, func(cr llm.CompletionResponse) {
			res := api.GenerateResponse{
285
286
				Model:      req.Model,
				CreatedAt:  time.Now().UTC(),
287
288
289
				Response:   cr.Content,
				Done:       cr.Done,
				DoneReason: cr.DoneReason,
Bruce MacDonald's avatar
Bruce MacDonald committed
290
				Metrics: api.Metrics{
291
292
293
294
					PromptEvalCount:    cr.PromptEvalCount,
					PromptEvalDuration: cr.PromptEvalDuration,
					EvalCount:          cr.EvalCount,
					EvalDuration:       cr.EvalDuration,
Bruce MacDonald's avatar
Bruce MacDonald committed
295
				},
Bruce MacDonald's avatar
Bruce MacDonald committed
296
			}
297
298
299
300
301
302
303
304
305
306

			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 {
307
					tokens, err := r.Tokenize(c.Request.Context(), prompt+sb.String())
308
309
310
311
					if err != nil {
						ch <- gin.H{"error": err.Error()}
						return
					}
312
					res.Context = tokens
313
314
315
316
				}
			}

			ch <- res
Michael Yang's avatar
Michael Yang committed
317
		}); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
318
319
320
321
322
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
Michael Yang's avatar
Michael Yang committed
323
		var r api.GenerateResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
324
		var sb strings.Builder
Michael Yang's avatar
Michael Yang committed
325
326
		for rr := range ch {
			switch t := rr.(type) {
327
			case api.GenerateResponse:
Michael Yang's avatar
Michael Yang committed
328
329
				sb.WriteString(t.Response)
				r = t
330
			case gin.H:
Michael Yang's avatar
Michael Yang committed
331
332
333
				msg, ok := t["error"].(string)
				if !ok {
					msg = "unexpected error format in response"
334
				}
Michael Yang's avatar
Michael Yang committed
335
336
337

				c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
				return
338
			default:
Michael Yang's avatar
Michael Yang committed
339
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
Bruce MacDonald's avatar
Bruce MacDonald committed
340
341
342
				return
			}
		}
343

Michael Yang's avatar
Michael Yang committed
344
345
		r.Response = sb.String()
		c.JSON(http.StatusOK, r)
Bruce MacDonald's avatar
Bruce MacDonald committed
346
347
348
349
350
351
		return
	}

	streamResponse(c, ch)
}

352
func (s *Server) EmbedHandler(c *gin.Context) {
353
	checkpointStart := time.Now()
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
	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:
387
388
389
390
		if req.Input != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid input type"})
			return
		}
391
392
393
394
395
396
397
398
	}

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

399
400
	checkpointLoaded := time.Now()

401
402
403
404
405
	if len(input) == 0 {
		c.JSON(http.StatusOK, api.EmbedResponse{Model: req.Model, Embeddings: [][]float32{}})
		return
	}

406
407
408
409
410
411
	kvData, err := getKVData(m.ModelPath, false)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

412
	var count int
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
	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
			}
		}

435
436
		count += len(tokens)

437
438
		input[i] = s
	}
439
440
441
442
443
444
445
446
447
448
449
450

	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
		})
451
452
	}

453
454
455
456
	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
457
458
459
	}

	resp := api.EmbedResponse{
460
		Model:           req.Model,
461
		Embeddings:      embeddings,
462
463
		TotalDuration:   time.Since(checkpointStart),
		LoadDuration:    checkpointLoaded.Sub(checkpointStart),
464
		PromptEvalCount: count,
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
	}
	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
486
func (s *Server) EmbeddingsHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
487
	var req api.EmbeddingRequest
Michael Yang's avatar
Michael Yang committed
488
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
Bruce MacDonald's avatar
Bruce MacDonald committed
489
490
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
491
	} else if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
492
493
494
495
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
496
	r, _, _, err := s.scheduleRunner(c.Request.Context(), req.Model, []Capability{}, req.Options, req.KeepAlive)
Bruce MacDonald's avatar
Bruce MacDonald committed
497
	if err != nil {
Michael Yang's avatar
Michael Yang committed
498
		handleScheduleError(c, req.Model, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
499
500
501
		return
	}

502
503
504
	// an empty request loads the model
	if req.Prompt == "" {
		c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: []float64{}})
Bruce MacDonald's avatar
Bruce MacDonald committed
505
506
507
		return
	}

508
	embedding, err := r.Embedding(c.Request.Context(), req.Prompt)
Bruce MacDonald's avatar
Bruce MacDonald committed
509
	if err != nil {
510
		slog.Info(fmt.Sprintf("embedding generation failed: %v", err))
511
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Errorf("failed to generate embedding: %v", err)})
Bruce MacDonald's avatar
Bruce MacDonald committed
512
513
514
		return
	}

515
516
517
	var e []float64
	for _, v := range embedding {
		e = append(e, float64(v))
518
519
520
	}

	resp := api.EmbeddingResponse{
521
		Embedding: e,
522
523
	}
	c.JSON(http.StatusOK, resp)
Bruce MacDonald's avatar
Bruce MacDonald committed
524
525
}

526
func (s *Server) PullHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
527
	var req api.PullRequest
Michael Yang's avatar
Michael Yang committed
528
529
530
531
532
533
534
	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
535
536
537
		return
	}

538
539
540
541
542
543
	name := model.ParseName(cmp.Or(req.Model, req.Name))
	if !name.IsValid() {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid model name"})
		return
	}

544
545
	name, err = getExistingName(name)
	if err != nil {
546
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
547
548
549
		return
	}

550
551
552
	ch := make(chan any)
	go func() {
		defer close(ch)
553
554
		fn := func(r api.ProgressResponse) {
			ch <- r
555
		}
556

Michael Yang's avatar
Michael Yang committed
557
		regOpts := &registryOptions{
558
559
560
			Insecure: req.Insecure,
		}

561
562
563
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

564
		if err := PullModel(ctx, name.DisplayShortest(), regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
565
			ch <- gin.H{"error": err.Error()}
566
567
568
		}
	}()

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

574
575
576
	streamResponse(c, ch)
}

577
func (s *Server) PushHandler(c *gin.Context) {
578
	var req api.PushRequest
Michael Yang's avatar
Michael Yang committed
579
580
581
582
583
584
585
	err := c.ShouldBindJSON(&req)
	switch {
	case errors.Is(err, io.EOF):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	case err != nil:
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
586
587
		return
	}
Michael Yang's avatar
Michael Yang committed
588

Michael Yang's avatar
Michael Yang committed
589
590
591
592
593
594
595
	var model string
	if req.Model != "" {
		model = req.Model
	} else if req.Name != "" {
		model = req.Name
	} else {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
596
597
598
		return
	}

599
600
601
	ch := make(chan any)
	go func() {
		defer close(ch)
602
603
		fn := func(r api.ProgressResponse) {
			ch <- r
604
		}
605

Michael Yang's avatar
Michael Yang committed
606
		regOpts := &registryOptions{
607
608
609
			Insecure: req.Insecure,
		}

Michael Yang's avatar
Michael Yang committed
610
611
612
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
613
		if err := PushModel(ctx, model, regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
614
			ch <- gin.H{"error": err.Error()}
615
616
617
		}
	}()

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

623
624
625
	streamResponse(c, ch)
}

626
627
628
629
630
// getExistingName returns the original, on disk name if the input name is a
// case-insensitive match, otherwise it returns the input name.
func getExistingName(n model.Name) (model.Name, error) {
	var zero model.Name
	existing, err := Manifests(true)
631
	if err != nil {
632
		return zero, err
633
	}
634
635
636
	for e := range existing {
		if n.EqualFold(e) {
			return e, nil
637
638
		}
	}
639
	return n, nil
640
641
}

642
func (s *Server) CreateHandler(c *gin.Context) {
643
644
	var r api.CreateRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
645
646
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
647
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
648
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
649
		return
650
651
	}

652
	name := model.ParseName(cmp.Or(r.Model, r.Name))
Michael Yang's avatar
Michael Yang committed
653
	if !name.IsValid() {
654
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": errtypes.InvalidModelNameErrMsg})
655
656
657
		return
	}

658
659
	name, err := getExistingName(name)
	if err != nil {
660
661
662
663
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

664
	if r.Path == "" && r.Modelfile == "" {
Michael Yang's avatar
Michael Yang committed
665
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
Michael Yang's avatar
Michael Yang committed
666
667
		return
	}
Michael Yang's avatar
Michael Yang committed
668

669
670
671
	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
672
673
674
675
		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
676
		defer f.Close()
Michael Yang's avatar
Michael Yang committed
677

678
		sr = f
Michael Yang's avatar
Michael Yang committed
679
	}
Michael Yang's avatar
Michael Yang committed
680

681
	f, err := parser.ParseFile(sr)
Michael Yang's avatar
Michael Yang committed
682
683
684
685
686
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
687
	ch := make(chan any)
Michael Yang's avatar
Michael Yang committed
688
689
	go func() {
		defer close(ch)
690
691
		fn := func(resp api.ProgressResponse) {
			ch <- resp
692
693
		}

694
695
696
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

697
		quantization := cmp.Or(r.Quantize, r.Quantization)
Josh's avatar
Josh committed
698
699
700
		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
701
			ch <- gin.H{"error": err.Error()}
702
		}
Michael Yang's avatar
Michael Yang committed
703
	}()
Michael Yang's avatar
Michael Yang committed
704

705
	if r.Stream != nil && !*r.Stream {
706
707
708
709
		waitForStream(c, ch)
		return
	}

Michael Yang's avatar
Michael Yang committed
710
	streamResponse(c, ch)
Bruce MacDonald's avatar
Bruce MacDonald committed
711
712
}

713
func (s *Server) DeleteHandler(c *gin.Context) {
714
715
	var r api.DeleteRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
716
717
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
718
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
719
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
720
721
722
		return
	}

723
724
725
	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))})
726
727
		return
	}
Michael Yang's avatar
Michael Yang committed
728

729
	m, err := ParseNamedManifest(n)
Michael Yang's avatar
Michael Yang committed
730
	if err != nil {
731
732
733
734
735
736
		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
737
738
739
		return
	}

740
	if err := m.Remove(); err != nil {
Michael Yang's avatar
Michael Yang committed
741
742
743
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
744
745
746
747
748

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

751
func (s *Server) ShowHandler(c *gin.Context) {
Patrick Devine's avatar
Patrick Devine committed
752
	var req api.ShowRequest
Michael Yang's avatar
Michael Yang committed
753
754
755
756
757
758
759
	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
760
761
762
		return
	}

Michael Yang's avatar
Michael Yang committed
763
	if req.Model != "" {
Michael Yang's avatar
Michael Yang committed
764
		// noop
Michael Yang's avatar
Michael Yang committed
765
	} else if req.Name != "" {
Michael Yang's avatar
Michael Yang committed
766
		req.Model = req.Name
Michael Yang's avatar
Michael Yang committed
767
	} else {
768
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
769
770
771
		return
	}

772
	resp, err := GetModelInfo(req)
Patrick Devine's avatar
Patrick Devine committed
773
	if err != nil {
774
775
		switch {
		case os.IsNotExist(err):
Michael Yang's avatar
Michael Yang committed
776
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
777
778
779
		case err.Error() == "invalid model name":
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
Patrick Devine's avatar
Patrick Devine committed
780
781
782
783
784
785
786
787
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

	c.JSON(http.StatusOK, resp)
}

788
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
789
	m, err := GetModel(req.Model)
Patrick Devine's avatar
Patrick Devine committed
790
791
792
793
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
794
	modelDetails := api.ModelDetails{
795
796
797
798
799
800
		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
801
802
	}

803
	if req.System != "" {
804
		m.System = req.System
805
806
	}

Michael Yang's avatar
Michael Yang committed
807
808
809
	msgs := make([]api.Message, len(m.Messages))
	for i, msg := range m.Messages {
		msgs[i] = api.Message{Role: msg.Role, Content: msg.Content}
810
811
	}

812
813
	n := model.ParseName(req.Model)
	if !n.IsValid() {
Michael Yang's avatar
lint  
Michael Yang committed
814
		return nil, errors.New("invalid model name")
815
816
817
818
819
820
821
	}

	manifest, err := ParseNamedManifest(n)
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
822
	resp := &api.ShowResponse{
823
824
		License:    strings.Join(m.License, "\n"),
		System:     m.System,
Michael Yang's avatar
Michael Yang committed
825
		Template:   m.Template.String(),
826
827
828
		Details:    modelDetails,
		Messages:   msgs,
		ModifiedAt: manifest.fi.ModTime(),
Patrick Devine's avatar
Patrick Devine committed
829
830
831
832
	}

	var params []string
	cs := 30
833
	for k, v := range m.Options {
Patrick Devine's avatar
Patrick Devine committed
834
835
836
		switch val := v.(type) {
		case []interface{}:
			for _, nv := range val {
Patrick Devine's avatar
Patrick Devine committed
837
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
Patrick Devine's avatar
Patrick Devine committed
838
			}
Patrick Devine's avatar
Patrick Devine committed
839
840
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
Patrick Devine's avatar
Patrick Devine committed
841
842
843
844
		}
	}
	resp.Parameters = strings.Join(params, "\n")

845
846
	for k, v := range req.Options {
		if _, ok := req.Options[k]; ok {
847
			m.Options[k] = v
848
849
850
		}
	}

851
	var sb strings.Builder
852
	fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"")
853
	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
854
855
	fmt.Fprintf(&sb, "# FROM %s\n\n", m.ShortName)
	fmt.Fprint(&sb, m.String())
856
	resp.Modelfile = sb.String()
857

858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
	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
874
875
876
	return resp, nil
}

877
func getKVData(digest string, verbose bool) (llm.KV, error) {
878
879
880
881
882
	maxArraySize := 0
	if verbose {
		maxArraySize = -1
	}
	kvData, err := llm.LoadModel(digest, maxArraySize)
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
	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
}

900
func (s *Server) ListHandler(c *gin.Context) {
901
	ms, err := Manifests(true)
Patrick Devine's avatar
Patrick Devine committed
902
903
904
905
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
906

907
	models := []api.ListModelResponse{}
908
909
	for n, m := range ms {
		var cf ConfigV2
910
911
912
913
914
915
916
917
918
919
920
921
922

		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
923
		}
Michael Yang's avatar
Michael Yang committed
924

925
		// tag should never be masked
926
		models = append(models, api.ListModelResponse{
927
928
929
930
931
932
933
934
935
936
937
938
939
			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
940
941
	}

942
	slices.SortStableFunc(models, func(i, j api.ListModelResponse) int {
943
944
945
946
		// most recently modified first
		return cmp.Compare(j.ModifiedAt.Unix(), i.ModifiedAt.Unix())
	})

Michael Yang's avatar
Michael Yang committed
947
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
948
949
}

950
func (s *Server) CopyHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
951
952
	var r api.CopyRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
953
954
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
955
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
956
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Patrick Devine's avatar
Patrick Devine committed
957
958
959
		return
	}

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

Michael Yang's avatar
Michael Yang committed
971
972
	dst := model.ParseName(r.Destination)
	if !dst.IsValid() {
973
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("destination %q is invalid", r.Destination)})
Patrick Devine's avatar
Patrick Devine committed
974
975
		return
	}
976
977
	dst, err = getExistingName(dst)
	if err != nil {
978
979
980
981
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
982
983
984
985
986
	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
987
988
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
989
func (s *Server) HeadBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
990
991
992
993
994
995
996
997
998
999
1000
	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
1001
	c.Status(http.StatusOK)
Michael Yang's avatar
Michael Yang committed
1002
1003
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1004
func (s *Server) CreateBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1005
1006
	if ib, ok := intermediateBlobs[c.Param("digest")]; ok {
		p, err := GetBlobsPath(ib)
1007
1008
1009
1010
1011
1012
		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
1013
1014
			slog.Info("evicting intermediate blob which no longer exists", "digest", ib)
			delete(intermediateBlobs, c.Param("digest"))
1015
1016
1017
1018
1019
1020
1021
1022
1023
		} else if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		} else {
			c.Status(http.StatusOK)
			return
		}
	}

1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
	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
	}

1042
	layer, err := NewLayer(c.Request.Body, "")
Michael Yang's avatar
Michael Yang committed
1043
1044
1045
1046
1047
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

1048
1049
	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
1050
1051
1052
		return
	}

Michael Yang's avatar
Michael Yang committed
1053
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
1054
1055
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
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
}

1077
func allowedHost(host string) bool {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1078
	if host == "" || host == "localhost" {
1079
1080
1081
1082
1083
1084
1085
		return true
	}

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

Michael Yang's avatar
lint  
Michael Yang committed
1086
	tlds := []string{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1087
1088
1089
		"localhost",
		"local",
		"internal",
1090
	}
1091

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1092
	// check if the host is a local TLD
1093
1094
1095
1096
1097
1098
	for _, tld := range tlds {
		if strings.HasSuffix(host, "."+tld) {
			return true
		}
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1099
	return false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1100
}
1101

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1102
1103
1104
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
	return func(c *gin.Context) {
		if addr == nil {
1105
1106
1107
1108
			c.Next()
			return
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1109
		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
1110
1111
1112
1113
1114
1115
1116
1117
1118
			c.Next()
			return
		}

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1119
		if addr, err := netip.ParseAddr(host); err == nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1120
			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1121
1122
1123
1124
1125
				c.Next()
				return
			}
		}

1126
		if allowedHost(host) {
Michael Yang's avatar
lint  
Michael Yang committed
1127
			if c.Request.Method == http.MethodOptions {
1128
1129
1130
1131
				c.AbortWithStatus(http.StatusNoContent)
				return
			}

1132
1133
1134
1135
1136
1137
			c.Next()
			return
		}

		c.AbortWithStatus(http.StatusForbidden)
	}
1138
}
1139

1140
func (s *Server) GenerateRoutes() http.Handler {
Michael Yang's avatar
Michael Yang committed
1141
1142
	config := cors.DefaultConfig()
	config.AllowWildcard = true
1143
	config.AllowBrowserExtensions = true
1144
	config.AllowHeaders = []string{"Authorization", "Content-Type", "User-Agent", "Accept", "X-Requested-With"}
1145
	openAIProperties := []string{"lang", "package-version", "os", "arch", "retry-count", "runtime", "runtime-version", "async"}
royjhan's avatar
royjhan committed
1146
1147
1148
	for _, prop := range openAIProperties {
		config.AllowHeaders = append(config.AllowHeaders, "x-stainless-"+prop)
	}
Michael Yang's avatar
origins  
Michael Yang committed
1149
	config.AllowOrigins = envconfig.Origins()
Michael Yang's avatar
Michael Yang committed
1150

Bruce MacDonald's avatar
Bruce MacDonald committed
1151
	r := gin.Default()
1152
1153
	r.Use(
		cors.New(config),
1154
		allowedHostsMiddleware(s.addr),
1155
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
1156

1157
	r.POST("/api/pull", s.PullHandler)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1158
1159
	r.POST("/api/generate", s.GenerateHandler)
	r.POST("/api/chat", s.ChatHandler)
1160
	r.POST("/api/embed", s.EmbedHandler)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1161
	r.POST("/api/embeddings", s.EmbeddingsHandler)
1162
1163
1164
1165
1166
	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
1167
1168
	r.POST("/api/blobs/:digest", s.CreateBlobHandler)
	r.HEAD("/api/blobs/:digest", s.HeadBlobHandler)
1169
	r.GET("/api/ps", s.PsHandler)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1170

1171
	// Compatibility endpoints
1172
	r.POST("/v1/chat/completions", openai.ChatMiddleware(), s.ChatHandler)
1173
	r.POST("/v1/completions", openai.CompletionsMiddleware(), s.GenerateHandler)
1174
	r.POST("/v1/embeddings", openai.EmbeddingsMiddleware(), s.EmbedHandler)
1175
1176
	r.GET("/v1/models", openai.ListMiddleware(), s.ListHandler)
	r.GET("/v1/models/:model", openai.RetrieveMiddleware(), s.ShowHandler)
1177

Michael Yang's avatar
Michael Yang committed
1178
1179
1180
1181
1182
	for _, method := range []string{http.MethodGet, http.MethodHead} {
		r.Handle(method, "/", func(c *gin.Context) {
			c.String(http.StatusOK, "Ollama is running")
		})

1183
		r.Handle(method, "/api/tags", s.ListHandler)
Michael Yang's avatar
Michael Yang committed
1184
1185
1186
		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
1187
1188
	}

1189
1190
1191
1192
	return r
}

func Serve(ln net.Listener) error {
Michael Yang's avatar
Michael Yang committed
1193
	level := slog.LevelInfo
Michael Yang's avatar
Michael Yang committed
1194
	if envconfig.Debug() {
Michael Yang's avatar
Michael Yang committed
1195
		level = slog.LevelDebug
1196
	}
Michael Yang's avatar
Michael Yang committed
1197

1198
	slog.Info("server config", "env", envconfig.Values())
Michael Yang's avatar
Michael Yang committed
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
	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))

1214
1215
1216
1217
1218
1219
1220
1221
	blobsDir, err := GetBlobsPath("")
	if err != nil {
		return err
	}
	if err := fixBlobs(blobsDir); err != nil {
		return err
	}

Michael Yang's avatar
bool  
Michael Yang committed
1222
	if !envconfig.NoPrune() {
1223
1224
1225
1226
1227
1228
1229
		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
			}
1230

1231
1232
1233
1234
			manifestsPath, err := GetManifestPath()
			if err != nil {
				return err
			}
1235

1236
1237
1238
			if err := PruneDirectory(manifestsPath); err != nil {
				return err
			}
1239
1240
1241
		}
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1242
	ctx, done := context.WithCancel(context.Background())
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1243
1244
	schedCtx, schedDone := context.WithCancel(ctx)
	sched := InitScheduler(schedCtx)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1245
	s := &Server{addr: ln.Addr(), sched: sched}
1246
1247

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

1249
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1250
	srvr := &http.Server{
1251
1252
1253
1254
1255
1256
1257
1258
1259
		// 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
1260
1261
	}

1262
1263
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
1264
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
1265
1266
	go func() {
		<-signals
1267
		srvr.Close()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1268
		schedDone()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1269
		sched.unloadAllRunners()
1270
		runners.Cleanup(build.EmbedFS)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1271
		done()
1272
1273
	}()

1274
1275
	if _, err := runners.Refresh(build.EmbedFS); err != nil {
		return fmt.Errorf("unable to initialize llm runners %w", err)
1276
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1277

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1278
	s.sched.Run(schedCtx)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1279
1280
1281

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

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

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

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

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

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

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

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

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

1379
1380
1381
		models = append(models, mr)
	}

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

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

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

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

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

Michael Yang's avatar
Michael Yang committed
1433
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), req.Model, caps, req.Options, req.KeepAlive)
Michael Yang's avatar
Michael Yang committed
1434
1435
	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
1436
		return
Michael Yang's avatar
Michael Yang committed
1437
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
1438
		handleScheduleError(c, req.Model, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
1439
1440
		return
	}
Michael Yang's avatar
Michael Yang committed
1441

1442
1443
	checkpointLoaded := time.Now()

Michael Yang's avatar
Michael Yang committed
1444
1445
	if len(req.Messages) == 0 {
		c.JSON(http.StatusOK, api.ChatResponse{
1446
			Model:      req.Model,
Michael Yang's avatar
Michael Yang committed
1447
1448
			CreatedAt:  time.Now().UTC(),
			Message:    api.Message{Role: "assistant"},
1449
1450
			Done:       true,
			DoneReason: "load",
Michael Yang's avatar
Michael Yang committed
1451
		})
1452
1453
1454
		return
	}

Michael Yang's avatar
Michael Yang committed
1455
	msgs := append(m.Messages, req.Messages...)
1456
	if req.Messages[0].Role != "system" && m.System != "" {
Michael Yang's avatar
Michael Yang committed
1457
		msgs = append([]api.Message{{Role: "system", Content: m.System}}, msgs...)
1458
1459
	}

Michael Yang's avatar
Michael Yang committed
1460
	prompt, images, err := chatPrompt(c.Request.Context(), m, r.Tokenize, opts, msgs, req.Tools)
Michael Yang's avatar
Michael Yang committed
1461
	if err != nil {
1462
		slog.Error("chat prompt error", "error", err)
Michael Yang's avatar
Michael Yang committed
1463
1464
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
1465
1466
	}

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

Bruce MacDonald's avatar
Bruce MacDonald committed
1469
1470
1471
	ch := make(chan any)
	go func() {
		defer close(ch)
1472
		var sb strings.Builder
1473
		var toolCallIndex int = 0
Michael Yang's avatar
Michael Yang committed
1474
		if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
Michael Yang's avatar
Michael Yang committed
1475
1476
1477
			Prompt:  prompt,
			Images:  images,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
1478
			Options: opts,
Michael Yang's avatar
Michael Yang committed
1479
		}, func(r llm.CompletionResponse) {
1480
			res := api.ChatResponse{
1481
1482
1483
1484
1485
				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
1486
1487
1488
1489
1490
1491
1492
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}
1493
1494
1495
1496
1497
1498

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

1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
			// 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
1513
1514
1515
1516
				for i := range toolCalls {
					toolCalls[i].Function.Index = toolCallIndex
					toolCallIndex++
				}
1517
1518
1519
1520
1521
1522
1523
1524
				res.Message.Content = ""
				sb.Reset()
				ch <- res
				return
			}

			if r.Done {
				// Send any remaining content if no tool calls were detected
1525
				if toolCallIndex == 0 {
1526
1527
1528
1529
					res.Message.Content = sb.String()
				}
				ch <- res
			}
Michael Yang's avatar
Michael Yang committed
1530
		}); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1531
1532
1533
1534
1535
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
Michael Yang's avatar
tools  
Michael Yang committed
1536
		var resp api.ChatResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
1537
		var sb strings.Builder
Michael Yang's avatar
Michael Yang committed
1538
1539
		for rr := range ch {
			switch t := rr.(type) {
1540
			case api.ChatResponse:
Michael Yang's avatar
Michael Yang committed
1541
				sb.WriteString(t.Message.Content)
Michael Yang's avatar
tools  
Michael Yang committed
1542
				resp = t
1543
			case gin.H:
Michael Yang's avatar
Michael Yang committed
1544
1545
1546
				msg, ok := t["error"].(string)
				if !ok {
					msg = "unexpected error format in response"
1547
				}
Michael Yang's avatar
Michael Yang committed
1548
1549
1550

				c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
				return
1551
			default:
Michael Yang's avatar
Michael Yang committed
1552
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
1553
				return
Bruce MacDonald's avatar
Bruce MacDonald committed
1554
1555
			}
		}
1556

Michael Yang's avatar
tools  
Michael Yang committed
1557
		resp.Message.Content = sb.String()
1558
1559
1560
1561
1562
1563

		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
1564
1565
1566
		}

		c.JSON(http.StatusOK, resp)
Bruce MacDonald's avatar
Bruce MacDonald committed
1567
1568
1569
1570
1571
		return
	}

	streamResponse(c, ch)
}
1572

Michael Yang's avatar
Michael Yang committed
1573
func handleScheduleError(c *gin.Context, name string, err error) {
Michael Yang's avatar
Michael Yang committed
1574
	switch {
1575
	case errors.Is(err, errCapabilities), errors.Is(err, errRequired):
Michael Yang's avatar
Michael Yang committed
1576
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
1577
	case errors.Is(err, context.Canceled):
1578
		c.JSON(499, gin.H{"error": "request canceled"})
Michael Yang's avatar
Michael Yang committed
1579
	case errors.Is(err, ErrMaxQueue):
1580
		c.JSON(http.StatusServiceUnavailable, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
1581
1582
	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
1583
1584
	default:
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
1585
1586
	}
}