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

import (
Michael Yang's avatar
Michael Yang committed
4
	"cmp"
5
	"context"
Michael Yang's avatar
Michael Yang committed
6
	"encoding/json"
7
	"errors"
8
	"fmt"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
9
	"io"
10
	"io/fs"
11
	"log/slog"
12
	"math"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
13
14
	"net"
	"net/http"
15
	"net/netip"
16
	"os"
17
	"os/signal"
Michael Yang's avatar
Michael Yang committed
18
	"path/filepath"
19
	"slices"
20
	"strconv"
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
27
	"github.com/gin-gonic/gin"

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

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

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

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

	gin.SetMode(mode)
}

59
60
var defaultSessionDuration = 5 * time.Minute

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

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

Daniel Hiltgen's avatar
Daniel Hiltgen committed
80
func (s *Server) GenerateHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
81
82
	checkpointStart := time.Now()
	var req api.GenerateRequest
Michael Yang's avatar
Michael Yang committed
83
	err := c.ShouldBindJSON(&req)
Patrick Devine's avatar
Patrick Devine committed
84

Michael Yang's avatar
Michael Yang committed
85
86
87
88
89
90
	switch {
	case errors.Is(err, io.EOF):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	case err != nil:
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
91
92
93
		return
	}

94
95
96
	// validate the request
	switch {
	case req.Model == "":
97
98
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
99
100
101
	case len(req.Format) > 0 && req.Format != "json":
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
		return
102
103
104
	case req.Raw && (req.Template != "" || req.System != "" || len(req.Context) > 0):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "raw mode does not support template, system, or context"})
		return
105
106
	}

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

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

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

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

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

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

Bruce MacDonald's avatar
Bruce MacDonald committed
152
	// an empty request loads the model
153
154
	// note: for a short while template was used in lieu
	// of `raw` mode so we need to check for it too
Bruce MacDonald's avatar
Bruce MacDonald committed
155
	if req.Prompt == "" && req.Template == "" && req.System == "" {
156
		c.JSON(http.StatusOK, api.GenerateResponse{
157
158
159
160
			CreatedAt:  time.Now().UTC(),
			Model:      req.Model,
			Done:       true,
			DoneReason: "load",
Michael Yang's avatar
Michael Yang committed
161
		})
Bruce MacDonald's avatar
Bruce MacDonald committed
162
163
164
		return
	}

Michael Yang's avatar
Michael Yang committed
165
166
167
168
169
170
	tmpl, err := template.Parse(req.Template)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
171
172
	checkpointLoaded := time.Now()

Bruce MacDonald's avatar
Bruce MacDonald committed
173
174
175
176
177
	var prompt string
	switch {
	case req.Raw:
		prompt = req.Prompt
	case req.Prompt != "":
178
		if req.Template == "" {
Michael Yang's avatar
Michael Yang committed
179
180
181
182
183
			model.Template, err = template.Parse(req.Template)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
Bruce MacDonald's avatar
Bruce MacDonald committed
184
185
		}

186
187
188
189
190
191
192
193
194
		if req.System == "" {
			req.System = model.System
		}

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

		var sb strings.Builder
Michael Yang's avatar
Michael Yang committed
195
196
197
198
199
200
		for i := range req.Images {
			fmt.Fprintf(&sb, "[img-%d] ", i)
		}

		sb.WriteString(req.Prompt)

Michael Yang's avatar
Michael Yang committed
201
		p, err := Prompt(tmpl, req.System, sb.String(), "", true)
Michael Yang's avatar
Michael Yang committed
202
203
204
205
206
207
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		sb.Reset()
Bruce MacDonald's avatar
Bruce MacDonald committed
208
		if req.Context != nil {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
209
			prev, err := runner.llama.Detokenize(c.Request.Context(), req.Context)
Bruce MacDonald's avatar
Bruce MacDonald committed
210
211
212
213
214
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}

215
			sb.WriteString(prev)
216
217
		}

218
219
220
		sb.WriteString(p)

		prompt = sb.String()
Bruce MacDonald's avatar
Bruce MacDonald committed
221
222
	}

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

Bruce MacDonald's avatar
Bruce MacDonald committed
225
	ch := make(chan any)
Bruce MacDonald's avatar
Bruce MacDonald committed
226
	var generated strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
227
228
229
	go func() {
		defer close(ch)

230
		fn := func(r llm.CompletionResponse) {
Bruce MacDonald's avatar
Bruce MacDonald committed
231
232
233
234
			// Build up the full response
			if _, err := generated.WriteString(r.Content); err != nil {
				ch <- gin.H{"error": err.Error()}
				return
Bruce MacDonald's avatar
Bruce MacDonald committed
235
236
			}

Bruce MacDonald's avatar
Bruce MacDonald committed
237
			resp := api.GenerateResponse{
238
239
240
241
242
				Model:      req.Model,
				CreatedAt:  time.Now().UTC(),
				Done:       r.Done,
				Response:   r.Content,
				DoneReason: r.DoneReason,
Bruce MacDonald's avatar
Bruce MacDonald committed
243
244
245
246
247
248
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
Bruce MacDonald's avatar
Bruce MacDonald committed
249
250
			}

251
252
253
254
255
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)

				if !req.Raw {
Michael Yang's avatar
Michael Yang committed
256
					p, err := Prompt(tmpl, req.System, req.Prompt, generated.String(), false)
257
					if err != nil {
258
						c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
259
260
						return
					}
261
262

					// TODO (jmorganca): encode() should not strip special tokens
Daniel Hiltgen's avatar
Daniel Hiltgen committed
263
					tokens, err := runner.llama.Tokenize(c.Request.Context(), p)
264
265
266
267
					if err != nil {
						ch <- gin.H{"error": err.Error()}
						return
					}
268
269

					resp.Context = append(req.Context, tokens...)
Bruce MacDonald's avatar
Bruce MacDonald committed
270
271
272
273
				}
			}

			ch <- resp
Bruce MacDonald's avatar
Bruce MacDonald committed
274
275
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
276
		var images []llm.ImageData
Michael Yang's avatar
Michael Yang committed
277
		for i := range req.Images {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
278
279
280
281
			images = append(images, llm.ImageData{
				ID:   i,
				Data: req.Images[i],
			})
Michael Yang's avatar
Michael Yang committed
282
283
		}

Bruce MacDonald's avatar
Bruce MacDonald committed
284
		// Start prediction
285
		req := llm.CompletionRequest{
286
287
			Prompt:  prompt,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
288
			Images:  images,
289
			Options: opts,
Bruce MacDonald's avatar
Bruce MacDonald committed
290
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
291
		if err := runner.llama.Completion(c.Request.Context(), req, fn); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
292
293
294
295
296
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
297
298
		// Accumulate responses into the final response
		var final api.GenerateResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
299
		var sb strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
300
		for resp := range ch {
301
302
303
304
305
306
307
308
309
310
311
312
313
314
			switch r := resp.(type) {
			case api.GenerateResponse:
				sb.WriteString(r.Response)
				final = r
			case gin.H:
				if errorMsg, ok := r["error"].(string); ok {
					c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
					return
				} else {
					c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in response"})
					return
				}
			default:
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error"})
Bruce MacDonald's avatar
Bruce MacDonald committed
315
316
317
				return
			}
		}
318
319
320

		final.Response = sb.String()
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
321
322
323
324
325
326
		return
	}

	streamResponse(c, ch)
}

327
func getDefaultSessionDuration() time.Duration {
328
329
	if envconfig.KeepAlive != "" {
		v, err := strconv.Atoi(envconfig.KeepAlive)
330
		if err != nil {
331
			d, err := time.ParseDuration(envconfig.KeepAlive)
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
			if err != nil {
				return defaultSessionDuration
			}

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

			return d
		}

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

	return defaultSessionDuration
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
353
func (s *Server) EmbeddingsHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
	var req api.EmbeddingRequest
	err := c.ShouldBindJSON(&req)
	switch {
	case errors.Is(err, io.EOF):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	case err != nil:
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if req.Model == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
	}

370
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
371
	if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
372
		var pErr *fs.PathError
373
		if errors.As(err, &pErr) {
Bruce MacDonald's avatar
Bruce MacDonald committed
374
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
375
376
377
378
379
380
381
382
383
384
385
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

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

	var sessionDuration time.Duration
	if req.KeepAlive == nil {
389
		sessionDuration = getDefaultSessionDuration()
390
391
392
393
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
394
395
396
397
398
	rCh, eCh := s.sched.GetRunner(c.Request.Context(), model, opts, sessionDuration)
	var runner *runnerRef
	select {
	case runner = <-rCh:
	case err = <-eCh:
399
		handleErrorResponse(c, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
400
401
402
		return
	}

403
404
405
	// an empty request loads the model
	if req.Prompt == "" {
		c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: []float64{}})
Bruce MacDonald's avatar
Bruce MacDonald committed
406
407
408
		return
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
409
	embedding, err := runner.llama.Embedding(c.Request.Context(), req.Prompt)
Bruce MacDonald's avatar
Bruce MacDonald committed
410
	if err != nil {
411
		slog.Info(fmt.Sprintf("embedding generation failed: %v", err))
Bruce MacDonald's avatar
Bruce MacDonald committed
412
413
414
415
416
417
418
419
420
421
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
		return
	}

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

Daniel Hiltgen's avatar
Daniel Hiltgen committed
422
func (s *Server) PullModelHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
423
	var req api.PullRequest
Michael Yang's avatar
Michael Yang committed
424
425
426
427
428
429
430
	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
431
432
433
		return
	}

434
435
436
437
438
439
440
441
	name := model.ParseName(cmp.Or(req.Model, req.Name))
	if !name.IsValid() {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid model name"})
		return
	}

	if err := checkNameExists(name); err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
442
443
444
		return
	}

445
446
447
	ch := make(chan any)
	go func() {
		defer close(ch)
448
449
		fn := func(r api.ProgressResponse) {
			ch <- r
450
		}
451

Michael Yang's avatar
Michael Yang committed
452
		regOpts := &registryOptions{
453
454
455
			Insecure: req.Insecure,
		}

456
457
458
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

459
		if err := PullModel(ctx, name.DisplayShortest(), regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
460
			ch <- gin.H{"error": err.Error()}
461
462
463
		}
	}()

464
465
466
467
468
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

469
470
471
	streamResponse(c, ch)
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
472
func (s *Server) PushModelHandler(c *gin.Context) {
473
	var req api.PushRequest
Michael Yang's avatar
Michael Yang committed
474
475
476
477
478
479
480
	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
481
482
		return
	}
Michael Yang's avatar
Michael Yang committed
483

Michael Yang's avatar
Michael Yang committed
484
485
486
487
488
489
490
	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"})
491
492
493
		return
	}

494
495
496
	ch := make(chan any)
	go func() {
		defer close(ch)
497
498
		fn := func(r api.ProgressResponse) {
			ch <- r
499
		}
500

Michael Yang's avatar
Michael Yang committed
501
		regOpts := &registryOptions{
502
503
504
			Insecure: req.Insecure,
		}

Michael Yang's avatar
Michael Yang committed
505
506
507
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
508
		if err := PushModel(ctx, model, regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
509
			ch <- gin.H{"error": err.Error()}
510
511
512
		}
	}()

513
514
515
516
517
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

518
519
520
	streamResponse(c, ch)
}

521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
func checkNameExists(name model.Name) error {
	names, err := Manifests()
	if err != nil {
		return err
	}

	for n := range names {
		if strings.EqualFold(n.Filepath(), name.Filepath()) && n != name {
			return fmt.Errorf("a model with that name already exists")
		}
	}

	return nil
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
536
func (s *Server) CreateModelHandler(c *gin.Context) {
537
538
	var r api.CreateRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
539
540
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
541
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
542
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
543
		return
544
545
	}

546
	name := model.ParseName(cmp.Or(r.Model, r.Name))
Michael Yang's avatar
Michael Yang committed
547
	if !name.IsValid() {
548
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": errtypes.InvalidModelNameErrMsg})
549
550
551
		return
	}

552
553
554
555
556
	if err := checkNameExists(name); err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

557
	if r.Path == "" && r.Modelfile == "" {
Michael Yang's avatar
Michael Yang committed
558
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
Michael Yang's avatar
Michael Yang committed
559
560
		return
	}
Michael Yang's avatar
Michael Yang committed
561

562
563
564
	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
565
566
567
568
		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
569
		defer f.Close()
Michael Yang's avatar
Michael Yang committed
570

571
		sr = f
Michael Yang's avatar
Michael Yang committed
572
	}
Michael Yang's avatar
Michael Yang committed
573

574
	f, err := parser.ParseFile(sr)
Michael Yang's avatar
Michael Yang committed
575
576
577
578
579
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
580
	ch := make(chan any)
Michael Yang's avatar
Michael Yang committed
581
582
	go func() {
		defer close(ch)
583
584
		fn := func(resp api.ProgressResponse) {
			ch <- resp
585
586
		}

587
588
589
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

590
591
		quantization := cmp.Or(r.Quantize, r.Quantization)
		if err := CreateModel(ctx, name, filepath.Dir(r.Path), strings.ToUpper(quantization), f, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
592
			ch <- gin.H{"error": err.Error()}
593
		}
Michael Yang's avatar
Michael Yang committed
594
	}()
Michael Yang's avatar
Michael Yang committed
595

596
	if r.Stream != nil && !*r.Stream {
597
598
599
600
		waitForStream(c, ch)
		return
	}

Michael Yang's avatar
Michael Yang committed
601
	streamResponse(c, ch)
Bruce MacDonald's avatar
Bruce MacDonald committed
602
603
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
604
func (s *Server) DeleteModelHandler(c *gin.Context) {
605
606
	var r api.DeleteRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
607
608
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
609
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
610
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
611
612
613
		return
	}

614
615
616
	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))})
617
618
		return
	}
Michael Yang's avatar
Michael Yang committed
619

620
	m, err := ParseNamedManifest(n)
Michael Yang's avatar
Michael Yang committed
621
622
623
624
625
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

626
	if err := m.Remove(); err != nil {
Michael Yang's avatar
Michael Yang committed
627
628
629
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
630
631
632
633
634

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

Daniel Hiltgen's avatar
Daniel Hiltgen committed
637
func (s *Server) ShowModelHandler(c *gin.Context) {
Patrick Devine's avatar
Patrick Devine committed
638
	var req api.ShowRequest
Michael Yang's avatar
Michael Yang committed
639
640
641
642
643
644
645
	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
646
647
648
		return
	}

Michael Yang's avatar
Michael Yang committed
649
	if req.Model != "" {
Michael Yang's avatar
Michael Yang committed
650
		// noop
Michael Yang's avatar
Michael Yang committed
651
	} else if req.Name != "" {
Michael Yang's avatar
Michael Yang committed
652
		req.Model = req.Name
Michael Yang's avatar
Michael Yang committed
653
	} else {
654
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
655
656
657
		return
	}

658
	resp, err := GetModelInfo(req)
Patrick Devine's avatar
Patrick Devine committed
659
	if err != nil {
660
661
		switch {
		case os.IsNotExist(err):
Michael Yang's avatar
Michael Yang committed
662
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
663
664
665
		case err.Error() == "invalid model name":
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
Patrick Devine's avatar
Patrick Devine committed
666
667
668
669
670
671
672
673
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

	c.JSON(http.StatusOK, resp)
}

674
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
675
	m, err := GetModel(req.Model)
Patrick Devine's avatar
Patrick Devine committed
676
677
678
679
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
680
	modelDetails := api.ModelDetails{
681
682
683
684
685
686
		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
687
688
	}

689
	if req.System != "" {
690
		m.System = req.System
691
692
693
	}

	if req.Template != "" {
Michael Yang's avatar
Michael Yang committed
694
695
696
697
		m.Template, err = template.Parse(req.Template)
		if err != nil {
			return nil, err
		}
698
699
	}

700
	msgs := make([]api.Message, 0)
701
	for _, msg := range m.Messages {
702
703
704
		msgs = append(msgs, api.Message{Role: msg.Role, Content: msg.Content})
	}

705
706
707
708
709
710
711
712
713
714
	n := model.ParseName(req.Model)
	if !n.IsValid() {
		return nil, fmt.Errorf("invalid model name")
	}

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

Patrick Devine's avatar
Patrick Devine committed
715
	resp := &api.ShowResponse{
716
717
		License:    strings.Join(m.License, "\n"),
		System:     m.System,
Michael Yang's avatar
Michael Yang committed
718
		Template:   m.Template.String(),
719
720
721
		Details:    modelDetails,
		Messages:   msgs,
		ModifiedAt: manifest.fi.ModTime(),
Patrick Devine's avatar
Patrick Devine committed
722
723
724
725
	}

	var params []string
	cs := 30
726
	for k, v := range m.Options {
Patrick Devine's avatar
Patrick Devine committed
727
728
729
		switch val := v.(type) {
		case []interface{}:
			for _, nv := range val {
Patrick Devine's avatar
Patrick Devine committed
730
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
Patrick Devine's avatar
Patrick Devine committed
731
			}
Patrick Devine's avatar
Patrick Devine committed
732
733
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
Patrick Devine's avatar
Patrick Devine committed
734
735
736
737
		}
	}
	resp.Parameters = strings.Join(params, "\n")

738
739
	for k, v := range req.Options {
		if _, ok := req.Options[k]; ok {
740
			m.Options[k] = v
741
742
743
		}
	}

744
	var sb strings.Builder
745
	fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"")
746
	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
747
748
	fmt.Fprintf(&sb, "# FROM %s\n\n", m.ShortName)
	fmt.Fprint(&sb, m.String())
749
	resp.Modelfile = sb.String()
750

751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
	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
767
768
769
	return resp, nil
}

770
func getKVData(digest string, verbose bool) (llm.KV, error) {
771
772
773
774
775
	maxArraySize := 0
	if verbose {
		maxArraySize = -1
	}
	kvData, err := llm.LoadModel(digest, maxArraySize)
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
	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
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
793
func (s *Server) ListModelsHandler(c *gin.Context) {
794
	ms, err := Manifests()
Patrick Devine's avatar
Patrick Devine committed
795
796
797
798
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
799

800
	models := []api.ListModelResponse{}
801
802
803
804
805
806
807
	for n, m := range ms {
		f, err := m.Config.Open()
		if err != nil {
			slog.Warn("bad manifest filepath", "name", n, "error", err)
			continue
		}
		defer f.Close()
808

809
810
811
812
		var cf ConfigV2
		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
813
		}
Michael Yang's avatar
Michael Yang committed
814

815
		// tag should never be masked
816
		models = append(models, api.ListModelResponse{
817
818
819
820
821
822
823
824
825
826
827
828
829
			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
830
831
	}

832
	slices.SortStableFunc(models, func(i, j api.ListModelResponse) int {
833
834
835
836
		// most recently modified first
		return cmp.Compare(j.ModifiedAt.Unix(), i.ModifiedAt.Unix())
	})

Michael Yang's avatar
Michael Yang committed
837
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
838
839
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
840
func (s *Server) CopyModelHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
841
842
	var r api.CopyRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
843
844
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
845
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
846
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Patrick Devine's avatar
Patrick Devine committed
847
848
849
		return
	}

Michael Yang's avatar
Michael Yang committed
850
851
	src := model.ParseName(r.Source)
	if !src.IsValid() {
Michael Yang's avatar
Michael Yang committed
852
853
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("source %q is invalid", r.Source)})
		return
854
855
	}

Michael Yang's avatar
Michael Yang committed
856
857
	dst := model.ParseName(r.Destination)
	if !dst.IsValid() {
858
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("destination %q is invalid", r.Destination)})
Patrick Devine's avatar
Patrick Devine committed
859
860
		return
	}
Michael Yang's avatar
Michael Yang committed
861

862
863
864
865
866
	if err := checkNameExists(dst); err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
867
868
869
870
871
	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
872
873
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
874
func (s *Server) HeadBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
875
876
877
878
879
880
881
882
883
884
885
	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
886
	c.Status(http.StatusOK)
Michael Yang's avatar
Michael Yang committed
887
888
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
889
func (s *Server) CreateBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
890
891
	if ib, ok := intermediateBlobs[c.Param("digest")]; ok {
		p, err := GetBlobsPath(ib)
892
893
894
895
896
897
		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
898
899
			slog.Info("evicting intermediate blob which no longer exists", "digest", ib)
			delete(intermediateBlobs, c.Param("digest"))
900
901
902
903
904
905
906
907
908
		} else if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		} else {
			c.Status(http.StatusOK)
			return
		}
	}

909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
	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
	}

927
	layer, err := NewLayer(c.Request.Body, "")
Michael Yang's avatar
Michael Yang committed
928
929
930
931
932
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

933
934
	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
935
936
937
		return
	}

Michael Yang's avatar
Michael Yang committed
938
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
939
940
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
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
}

962
func allowedHost(host string) bool {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
963
	if host == "" || host == "localhost" {
964
965
966
967
968
969
970
971
		return true
	}

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

	var tlds = []string{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
972
973
974
		"localhost",
		"local",
		"internal",
975
	}
976

Jeffrey Morgan's avatar
Jeffrey Morgan committed
977
	// check if the host is a local TLD
978
979
980
981
982
983
	for _, tld := range tlds {
		if strings.HasSuffix(host, "."+tld) {
			return true
		}
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
984
	return false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
985
}
986

Jeffrey Morgan's avatar
Jeffrey Morgan committed
987
988
989
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
	return func(c *gin.Context) {
		if addr == nil {
990
991
992
993
			c.Next()
			return
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
994
		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
995
996
997
998
999
1000
1001
1002
1003
			c.Next()
			return
		}

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1004
		if addr, err := netip.ParseAddr(host); err == nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1005
			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1006
1007
1008
1009
1010
				c.Next()
				return
			}
		}

1011
		if allowedHost(host) {
Michael Yang's avatar
lint  
Michael Yang committed
1012
			if c.Request.Method == http.MethodOptions {
1013
1014
1015
1016
				c.AbortWithStatus(http.StatusNoContent)
				return
			}

1017
1018
1019
1020
1021
1022
			c.Next()
			return
		}

		c.AbortWithStatus(http.StatusForbidden)
	}
1023
}
1024

1025
func (s *Server) GenerateRoutes() http.Handler {
Michael Yang's avatar
Michael Yang committed
1026
1027
	config := cors.DefaultConfig()
	config.AllowWildcard = true
1028
	config.AllowBrowserExtensions = true
1029
	config.AllowHeaders = []string{"Authorization", "Content-Type", "User-Agent", "Accept", "X-Requested-With"}
royjhan's avatar
royjhan committed
1030
1031
1032
1033
	openAIProperties := []string{"lang", "package-version", "os", "arch", "runtime", "runtime-version", "async"}
	for _, prop := range openAIProperties {
		config.AllowHeaders = append(config.AllowHeaders, "x-stainless-"+prop)
	}
1034
	config.AllowOrigins = envconfig.AllowOrigins
Michael Yang's avatar
Michael Yang committed
1035

Bruce MacDonald's avatar
Bruce MacDonald committed
1036
	r := gin.Default()
1037
1038
	r.Use(
		cors.New(config),
1039
		allowedHostsMiddleware(s.addr),
1040
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
1041

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
	r.POST("/api/pull", s.PullModelHandler)
	r.POST("/api/generate", s.GenerateHandler)
	r.POST("/api/chat", s.ChatHandler)
	r.POST("/api/embeddings", s.EmbeddingsHandler)
	r.POST("/api/create", s.CreateModelHandler)
	r.POST("/api/push", s.PushModelHandler)
	r.POST("/api/copy", s.CopyModelHandler)
	r.DELETE("/api/delete", s.DeleteModelHandler)
	r.POST("/api/show", s.ShowModelHandler)
	r.POST("/api/blobs/:digest", s.CreateBlobHandler)
	r.HEAD("/api/blobs/:digest", s.HeadBlobHandler)
1053
	r.GET("/api/ps", s.ProcessHandler)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1054

1055
	// Compatibility endpoints
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1056
	r.POST("/v1/chat/completions", openai.Middleware(), s.ChatHandler)
1057

Michael Yang's avatar
Michael Yang committed
1058
1059
1060
1061
1062
	for _, method := range []string{http.MethodGet, http.MethodHead} {
		r.Handle(method, "/", func(c *gin.Context) {
			c.String(http.StatusOK, "Ollama is running")
		})

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1063
		r.Handle(method, "/api/tags", s.ListModelsHandler)
Michael Yang's avatar
Michael Yang committed
1064
1065
1066
		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
1067
1068
	}

1069
1070
1071
1072
	return r
}

func Serve(ln net.Listener) error {
Michael Yang's avatar
Michael Yang committed
1073
	level := slog.LevelInfo
1074
	if envconfig.Debug {
Michael Yang's avatar
Michael Yang committed
1075
		level = slog.LevelDebug
1076
	}
Michael Yang's avatar
Michael Yang committed
1077

1078
	slog.Info("server config", "env", envconfig.Values())
Michael Yang's avatar
Michael Yang committed
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
	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))

1094
1095
1096
1097
1098
1099
1100
1101
	blobsDir, err := GetBlobsPath("")
	if err != nil {
		return err
	}
	if err := fixBlobs(blobsDir); err != nil {
		return err
	}

1102
	if !envconfig.NoPrune {
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
		// clean up unused layers and manifests
		if err := PruneLayers(); err != nil {
			return err
		}

		manifestsPath, err := GetManifestPath()
		if err != nil {
			return err
		}

		if err := PruneDirectory(manifestsPath); err != nil {
			return err
		}
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1118
	ctx, done := context.WithCancel(context.Background())
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1119
1120
	schedCtx, schedDone := context.WithCancel(ctx)
	sched := InitScheduler(schedCtx)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1121
	s := &Server{addr: ln.Addr(), sched: sched}
1122
1123

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

1125
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1126
	srvr := &http.Server{
1127
1128
1129
1130
1131
1132
1133
1134
1135
		// 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
1136
1137
	}

1138
1139
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
1140
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
1141
1142
	go func() {
		<-signals
1143
		srvr.Close()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1144
		schedDone()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1145
		sched.unloadAllRunners()
1146
		gpu.Cleanup()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1147
		done()
1148
1149
	}()

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1150
	if err := llm.Init(); err != nil {
1151
1152
		return fmt.Errorf("unable to initialize llm library %w", err)
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1153

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1154
	s.sched.Run(schedCtx)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1155
1156
1157

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

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1161
1162
1163
1164
1165
1166
1167
	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()
1168
	return nil
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1169
}
Michael Yang's avatar
Michael Yang committed
1170

1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
func waitForStream(c *gin.Context, ch chan interface{}) {
	c.Header("Content-Type", "application/json")
	for resp := range ch {
		switch r := resp.(type) {
		case api.ProgressResponse:
			if r.Status == "success" {
				c.JSON(http.StatusOK, r)
				return
			}
		case gin.H:
			if errorMsg, ok := r["error"].(string); ok {
				c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
				return
			} else {
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
				return
			}
		default:
			c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
			return
		}
	}
	c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
}

Michael Yang's avatar
Michael Yang committed
1196
func streamResponse(c *gin.Context, ch chan any) {
1197
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
1198
1199
1200
1201
1202
1203
1204
1205
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

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

1210
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
1211
1212
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
1213
			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1214
1215
1216
1217
1218
1219
			return false
		}

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

1221
func (s *Server) ProcessHandler(c *gin.Context) {
1222
	models := []api.ProcessModelResponse{}
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233

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

1234
		mr := api.ProcessModelResponse{
1235
1236
1237
1238
1239
1240
1241
1242
			Model:     model.ShortName,
			Name:      model.ShortName,
			Size:      int64(v.estimatedTotal),
			SizeVRAM:  int64(v.estimatedVRAM),
			Digest:    model.Digest,
			Details:   modelDetails,
			ExpiresAt: v.expiresAt,
		}
1243
1244
1245
1246
1247
1248
1249
1250
		// 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)
		}

1251
1252
1253
		models = append(models, mr)
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1254
1255
1256
1257
1258
	slices.SortStableFunc(models, func(i, j api.ProcessModelResponse) int {
		// longest duration remaining listed first
		return cmp.Compare(j.ExpiresAt.Unix(), i.ExpiresAt.Unix())
	})

1259
	c.JSON(http.StatusOK, api.ProcessResponse{Models: models})
1260
1261
}

1262
// ChatPrompt builds up a prompt from a series of messages for the currently `loaded` model
Michael Yang's avatar
Michael Yang committed
1263
func chatPrompt(ctx context.Context, runner *runnerRef, template *template.Template, messages []api.Message, numCtx int) (string, error) {
1264
	encode := func(s string) ([]int, error) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1265
		return runner.llama.Tokenize(ctx, s)
1266
1267
	}

1268
	prompt, err := ChatPrompt(template, messages, numCtx, encode)
1269
1270
1271
1272
1273
1274
1275
	if err != nil {
		return "", err
	}

	return prompt, nil
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1276
func (s *Server) ChatHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
	checkpointStart := time.Now()

	var req api.ChatRequest
	err := c.ShouldBindJSON(&req)
	switch {
	case errors.Is(err, io.EOF):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	case err != nil:
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// validate the request
	switch {
	case req.Model == "":
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
	case len(req.Format) > 0 && req.Format != "json":
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
		return
	}

1300
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
1301
1302
	if err != nil {
		var pErr *fs.PathError
1303
		if errors.As(err, &pErr) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1304
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
1305
1306
1307
1308
1309
1310
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

1311
	if model.IsEmbedding() {
1312
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "embedding models do not support chat"})
1313
1314
1315
		return
	}

1316
1317
1318
1319
1320
	opts, err := modelOptions(model, req.Options)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
1321
1322
1323

	var sessionDuration time.Duration
	if req.KeepAlive == nil {
1324
		sessionDuration = getDefaultSessionDuration()
1325
1326
1327
1328
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1329
1330
1331
1332
1333
	rCh, eCh := s.sched.GetRunner(c.Request.Context(), model, opts, sessionDuration)
	var runner *runnerRef
	select {
	case runner = <-rCh:
	case err = <-eCh:
1334
		handleErrorResponse(c, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
1335
1336
1337
1338
1339
		return
	}

	checkpointLoaded := time.Now()

1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
	// if the first message is not a system message, then add the model's default system message
	if len(req.Messages) > 0 && req.Messages[0].Role != "system" {
		req.Messages = append([]api.Message{
			{
				Role:    "system",
				Content: model.System,
			},
		}, req.Messages...)
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1350
	prompt, err := chatPrompt(c.Request.Context(), runner, model.Template, req.Messages, opts.NumCtx)
Bruce MacDonald's avatar
Bruce MacDonald committed
1351
1352
1353
1354
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
1355

1356
	// an empty request loads the model
1357
	if len(req.Messages) == 0 || prompt == "" {
1358
		resp := api.ChatResponse{
1359
1360
1361
1362
1363
			CreatedAt:  time.Now().UTC(),
			Model:      req.Model,
			Done:       true,
			DoneReason: "load",
			Message:    api.Message{Role: "assistant"},
1364
1365
1366
1367
1368
		}
		c.JSON(http.StatusOK, resp)
		return
	}

1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
	// only send images that are in the prompt
	var i int
	var images []llm.ImageData
	for _, m := range req.Messages {
		for _, img := range m.Images {
			if !isSupportedImageType(img) {
				c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "unsupported image format"})
				return
			}

			if strings.Contains(prompt, fmt.Sprintf("[img-%d]", i)) {
				images = append(images, llm.ImageData{Data: img, ID: i})
			}
			i += 1
		}
	}

	slog.Debug("chat handler", "prompt", prompt, "images", len(images))
1387

Bruce MacDonald's avatar
Bruce MacDonald committed
1388
1389
1390
1391
1392
	ch := make(chan any)

	go func() {
		defer close(ch)

1393
		fn := func(r llm.CompletionResponse) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1394
			resp := api.ChatResponse{
1395
1396
1397
1398
1399
				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
1400
1401
1402
1403
1404
1405
1406
1407
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}

1408
1409
1410
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
Bruce MacDonald's avatar
Bruce MacDonald committed
1411
1412
1413
1414
1415
			}

			ch <- resp
		}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1416
		if err := runner.llama.Completion(c.Request.Context(), llm.CompletionRequest{
1417
1418
			Prompt:  prompt,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
1419
			Images:  images,
1420
			Options: opts,
1421
		}, fn); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1422
1423
1424
1425
1426
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
1427
1428
		// Accumulate responses into the final response
		var final api.ChatResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
1429
1430
		var sb strings.Builder
		for resp := range ch {
1431
1432
			switch r := resp.(type) {
			case api.ChatResponse:
1433
				sb.WriteString(r.Message.Content)
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
				final = r
			case gin.H:
				if errorMsg, ok := r["error"].(string); ok {
					c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
					return
				} else {
					c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in response"})
					return
				}
			default:
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error"})
				return
Bruce MacDonald's avatar
Bruce MacDonald committed
1446
1447
			}
		}
1448

1449
		final.Message = api.Message{Role: "assistant", Content: sb.String()}
1450
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
1451
1452
1453
1454
1455
		return
	}

	streamResponse(c, ch)
}
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467

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