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

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

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

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

Michael Yang's avatar
Michael Yang committed
36
37
var mode string = gin.DebugMode

38
type Server struct {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
39
40
	addr  net.Addr
	sched *Scheduler
41
42
}

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

	gin.SetMode(mode)
}

55
56
var defaultSessionDuration = 5 * time.Minute

57
58
59
60
61
62
63
64
65
66
67
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
68
69
}

70
71
72
73
74
75
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
76
func (s *Server) GenerateHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
77
78
79

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

Michael Yang's avatar
Michael Yang committed
82
83
84
85
86
87
	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
88
89
90
		return
	}

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

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

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

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

127
128
129
	opts, err := modelOptions(model, req.Options)
	if err != nil {
		if errors.Is(err, api.ErrInvalidOpts) {
Bruce MacDonald's avatar
Bruce MacDonald committed
130
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
131
			return
132
		}
133
134
135
136
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

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

Daniel Hiltgen's avatar
Daniel Hiltgen committed
144
145
146
147
148
	rCh, eCh := s.sched.GetRunner(c.Request.Context(), model, opts, sessionDuration)
	var runner *runnerRef
	select {
	case runner = <-rCh:
	case err = <-eCh:
149
150
151
152
153
		if errors.Is(err, context.Canceled) {
			c.JSON(499, gin.H{"error": "request canceled"})
			return
		}

154
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
155
156
157
		return
	}

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

	checkpointLoaded := time.Now()

Bruce MacDonald's avatar
Bruce MacDonald committed
172
173
174
175
176
	var prompt string
	switch {
	case req.Raw:
		prompt = req.Prompt
	case req.Prompt != "":
177
178
		if req.Template == "" {
			req.Template = model.Template
Bruce MacDonald's avatar
Bruce MacDonald committed
179
180
		}

181
182
183
184
185
186
187
188
189
		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
190
191
192
193
194
195
196
197
198
199
200
201
202
		for i := range req.Images {
			fmt.Fprintf(&sb, "[img-%d] ", i)
		}

		sb.WriteString(req.Prompt)

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

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

210
			sb.WriteString(prev)
211
212
		}

213
214
215
		sb.WriteString(p)

		prompt = sb.String()
Bruce MacDonald's avatar
Bruce MacDonald committed
216
217
	}

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

Bruce MacDonald's avatar
Bruce MacDonald committed
220
	ch := make(chan any)
Bruce MacDonald's avatar
Bruce MacDonald committed
221
	var generated strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
222
223
224
	go func() {
		defer close(ch)

225
		fn := func(r llm.CompletionResponse) {
Bruce MacDonald's avatar
Bruce MacDonald committed
226
227
228
229
			// 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
230
231
			}

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

245
246
247
248
249
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)

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

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

					resp.Context = append(req.Context, tokens...)
Bruce MacDonald's avatar
Bruce MacDonald committed
264
265
266
267
				}
			}

			ch <- resp
Bruce MacDonald's avatar
Bruce MacDonald committed
268
269
		}

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

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

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

		final.Response = sb.String()
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
315
316
317
318
319
320
		return
	}

	streamResponse(c, ch)
}

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

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

			return d
		}

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

	return defaultSessionDuration
}

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

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

	opts, err := modelOptions(model, req.Options)
	if err != nil {
		if errors.Is(err, api.ErrInvalidOpts) {
Bruce MacDonald's avatar
Bruce MacDonald committed
378
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
379
			return
Bruce MacDonald's avatar
Bruce MacDonald committed
380
		}
381
382
383
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
384
385
386

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

Daniel Hiltgen's avatar
Daniel Hiltgen committed
392
393
394
395
396
	rCh, eCh := s.sched.GetRunner(c.Request.Context(), model, opts, sessionDuration)
	var runner *runnerRef
	select {
	case runner = <-rCh:
	case err = <-eCh:
397
398
399
400
401
		if errors.Is(err, context.Canceled) {
			c.JSON(499, gin.H{"error": "request canceled"})
			return
		}

402
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
403
404
405
		return
	}

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

Daniel Hiltgen's avatar
Daniel Hiltgen committed
412
	embedding, err := runner.llama.Embedding(c.Request.Context(), req.Prompt)
Bruce MacDonald's avatar
Bruce MacDonald committed
413
	if err != nil {
414
		slog.Info(fmt.Sprintf("embedding generation failed: %v", err))
Bruce MacDonald's avatar
Bruce MacDonald committed
415
416
417
418
419
420
421
422
423
424
		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
425
func (s *Server) PullModelHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
426
	var req api.PullRequest
Michael Yang's avatar
Michael Yang committed
427
428
429
430
431
432
433
	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
434
435
436
		return
	}

Michael Yang's avatar
Michael Yang committed
437
438
439
440
441
442
443
	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"})
444
445
446
		return
	}

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

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

458
459
460
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

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

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

471
472
473
	streamResponse(c, ch)
}

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

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

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

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

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

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

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

520
521
522
	streamResponse(c, ch)
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
523
func (s *Server) CreateModelHandler(c *gin.Context) {
524
	var req api.CreateRequest
Michael Yang's avatar
Michael Yang committed
525
526
527
528
529
530
531
	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
532
		return
533
534
	}

Michael Yang's avatar
Michael Yang committed
535
536
537
538
539
540
541
	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"})
542
543
544
		return
	}

Michael Yang's avatar
Michael Yang committed
545
	if err := ParseModelPath(model).Validate(); err != nil {
546
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
547
548
549
		return
	}

Michael Yang's avatar
Michael Yang committed
550
551
	if req.Path == "" && req.Modelfile == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
Michael Yang's avatar
Michael Yang committed
552
553
		return
	}
Michael Yang's avatar
Michael Yang committed
554
555
556

	var modelfile io.Reader = strings.NewReader(req.Modelfile)
	if req.Path != "" && req.Modelfile == "" {
557
		mf, err := os.Open(req.Path)
Michael Yang's avatar
Michael Yang committed
558
559
560
561
		if err != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
			return
		}
562
		defer mf.Close()
Michael Yang's avatar
Michael Yang committed
563

564
		modelfile = mf
Michael Yang's avatar
Michael Yang committed
565
	}
Michael Yang's avatar
Michael Yang committed
566
567
568
569
570
571
572

	commands, err := parser.Parse(modelfile)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
573
	ch := make(chan any)
Michael Yang's avatar
Michael Yang committed
574
575
	go func() {
		defer close(ch)
576
577
		fn := func(resp api.ProgressResponse) {
			ch <- resp
578
579
		}

580
581
582
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
583
		if err := CreateModel(ctx, model, filepath.Dir(req.Path), req.Quantization, commands, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
584
			ch <- gin.H{"error": err.Error()}
585
		}
Michael Yang's avatar
Michael Yang committed
586
	}()
Michael Yang's avatar
Michael Yang committed
587

588
589
590
591
592
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

Michael Yang's avatar
Michael Yang committed
593
	streamResponse(c, ch)
Bruce MacDonald's avatar
Bruce MacDonald committed
594
595
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
596
func (s *Server) DeleteModelHandler(c *gin.Context) {
597
	var req api.DeleteRequest
Michael Yang's avatar
Michael Yang committed
598
599
600
601
602
603
604
	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()})
605
606
607
		return
	}

Michael Yang's avatar
Michael Yang committed
608
609
610
611
612
613
614
	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"})
615
616
617
		return
	}

Michael Yang's avatar
Michael Yang committed
618
	if err := DeleteModel(model); err != nil {
619
		if os.IsNotExist(err) {
Michael Yang's avatar
Michael Yang committed
620
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", model)})
621
		} else {
622
623
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
624
625
		return
	}
Michael Yang's avatar
Michael Yang committed
626
627
628
629
630
631
632
633
634
635
636
637

	manifestsPath, err := GetManifestPath()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if err := PruneDirectory(manifestsPath); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

638
	c.JSON(http.StatusOK, nil)
639
640
}

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

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

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

	c.JSON(http.StatusOK, resp)
}

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

Patrick Devine's avatar
Patrick Devine committed
681
	modelDetails := api.ModelDetails{
682
		ParentModel:       model.ParentModel,
Patrick Devine's avatar
Patrick Devine committed
683
684
685
686
687
688
689
		Format:            model.Config.ModelFormat,
		Family:            model.Config.ModelFamily,
		Families:          model.Config.ModelFamilies,
		ParameterSize:     model.Config.ModelType,
		QuantizationLevel: model.Config.FileType,
	}

690
691
692
693
694
695
696
697
	if req.System != "" {
		model.System = req.System
	}

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

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

Patrick Devine's avatar
Patrick Devine committed
703
704
705
706
	resp := &api.ShowResponse{
		License:  strings.Join(model.License, "\n"),
		System:   model.System,
		Template: model.Template,
Patrick Devine's avatar
Patrick Devine committed
707
		Details:  modelDetails,
708
		Messages: msgs,
Patrick Devine's avatar
Patrick Devine committed
709
710
711
712
713
714
715
716
	}

	var params []string
	cs := 30
	for k, v := range model.Options {
		switch val := v.(type) {
		case []interface{}:
			for _, nv := range val {
Patrick Devine's avatar
Patrick Devine committed
717
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
Patrick Devine's avatar
Patrick Devine committed
718
			}
Patrick Devine's avatar
Patrick Devine committed
719
720
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
Patrick Devine's avatar
Patrick Devine committed
721
722
723
724
		}
	}
	resp.Parameters = strings.Join(params, "\n")

725
726
727
728
729
730
	for k, v := range req.Options {
		if _, ok := req.Options[k]; ok {
			model.Options[k] = v
		}
	}

731
732
733
734
735
736
	var sb strings.Builder
	fmt.Fprintln(&sb, "# Modelfile generate by \"ollama show\"")
	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
	fmt.Fprintf(&sb, "# FROM %s\n\n", model.ShortName)
	fmt.Fprint(&sb, parser.Format(model.Commands()))
	resp.Modelfile = sb.String()
737

Patrick Devine's avatar
Patrick Devine committed
738
739
740
	return resp, nil
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
741
func (s *Server) ListModelsHandler(c *gin.Context) {
742
	models := make([]api.ModelResponse, 0)
743
	manifestsPath, err := GetManifestPath()
Patrick Devine's avatar
Patrick Devine committed
744
745
746
747
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
748

Patrick Devine's avatar
Patrick Devine committed
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
	modelResponse := func(modelName string) (api.ModelResponse, error) {
		model, err := GetModel(modelName)
		if err != nil {
			return api.ModelResponse{}, err
		}

		modelDetails := api.ModelDetails{
			Format:            model.Config.ModelFormat,
			Family:            model.Config.ModelFamily,
			Families:          model.Config.ModelFamilies,
			ParameterSize:     model.Config.ModelType,
			QuantizationLevel: model.Config.FileType,
		}

		return api.ModelResponse{
Michael Yang's avatar
Michael Yang committed
764
			Model:   model.ShortName,
Patrick Devine's avatar
Patrick Devine committed
765
766
767
768
769
770
771
			Name:    model.ShortName,
			Size:    model.Size,
			Digest:  model.Digest,
			Details: modelDetails,
		}, nil
	}

Michael Yang's avatar
Michael Yang committed
772
	walkFunc := func(path string, info os.FileInfo, _ error) error {
Patrick Devine's avatar
Patrick Devine committed
773
		if !info.IsDir() {
774
775
776
777
			path, tag := filepath.Split(path)
			model := strings.Trim(strings.TrimPrefix(path, manifestsPath), string(os.PathSeparator))
			modelPath := strings.Join([]string{model, tag}, ":")
			canonicalModelPath := strings.ReplaceAll(modelPath, string(os.PathSeparator), "/")
778

779
			resp, err := modelResponse(canonicalModelPath)
Patrick Devine's avatar
Patrick Devine committed
780
			if err != nil {
781
				slog.Info(fmt.Sprintf("skipping file: %s", canonicalModelPath))
Michael Yang's avatar
Michael Yang committed
782
				// nolint: nilerr
783
				return nil
Patrick Devine's avatar
Patrick Devine committed
784
			}
Michael Yang's avatar
Michael Yang committed
785

Patrick Devine's avatar
Patrick Devine committed
786
787
			resp.ModifiedAt = info.ModTime()
			models = append(models, resp)
Patrick Devine's avatar
Patrick Devine committed
788
		}
Michael Yang's avatar
Michael Yang committed
789

Patrick Devine's avatar
Patrick Devine committed
790
		return nil
Michael Yang's avatar
Michael Yang committed
791
792
	}

793
	if err := filepath.Walk(manifestsPath, walkFunc); err != nil {
Patrick Devine's avatar
Patrick Devine committed
794
795
796
797
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

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

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

Michael Yang's avatar
Michael Yang committed
811
812
813
	src := model.ParseName(r.Source)
	if !src.IsValid() {
		_ = c.Error(fmt.Errorf("source %q is invalid", r.Source))
814
815
	}

Michael Yang's avatar
Michael Yang committed
816
817
818
	dst := model.ParseName(r.Destination)
	if !dst.IsValid() {
		_ = c.Error(fmt.Errorf("destination %q is invalid", r.Destination))
819
820
	}

Michael Yang's avatar
Michael Yang committed
821
822
	if len(c.Errors) > 0 {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": c.Errors.Errors()})
Patrick Devine's avatar
Patrick Devine committed
823
824
		return
	}
Michael Yang's avatar
Michael Yang committed
825
826
827
828
829
830

	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
831
832
}

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

Daniel Hiltgen's avatar
Daniel Hiltgen committed
848
func (s *Server) CreateBlobHandler(c *gin.Context) {
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
	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
	}

867
	layer, err := NewLayer(c.Request.Body, "")
Michael Yang's avatar
Michael Yang committed
868
869
870
871
872
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

873
874
	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
875
876
877
		return
	}

878
	if _, err := layer.Commit(); err != nil {
Michael Yang's avatar
Michael Yang committed
879
880
881
882
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
883
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
884
885
}

Michael Yang's avatar
Michael Yang committed
886
887
888
889
890
891
var defaultAllowOrigins = []string{
	"localhost",
	"127.0.0.1",
	"0.0.0.0",
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
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
}

913
func allowedHost(host string) bool {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
914
	if host == "" || host == "localhost" {
915
916
917
918
919
920
921
922
		return true
	}

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

	var tlds = []string{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
923
924
925
		"localhost",
		"local",
		"internal",
926
	}
927

Jeffrey Morgan's avatar
Jeffrey Morgan committed
928
	// check if the host is a local TLD
929
930
931
932
933
934
	for _, tld := range tlds {
		if strings.HasSuffix(host, "."+tld) {
			return true
		}
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
935
	return false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
936
}
937

Jeffrey Morgan's avatar
Jeffrey Morgan committed
938
939
940
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
	return func(c *gin.Context) {
		if addr == nil {
941
942
943
944
			c.Next()
			return
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
945
		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
946
947
948
949
950
951
952
953
954
			c.Next()
			return
		}

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
955
		if addr, err := netip.ParseAddr(host); err == nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
956
			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
957
958
959
960
961
				c.Next()
				return
			}
		}

962
963
964
965
966
967
968
		if allowedHost(host) {
			c.Next()
			return
		}

		c.AbortWithStatus(http.StatusForbidden)
	}
969
}
970

971
func (s *Server) GenerateRoutes() http.Handler {
Michael Yang's avatar
Michael Yang committed
972
973
	config := cors.DefaultConfig()
	config.AllowWildcard = true
974
	config.AllowBrowserExtensions = true
Michael Yang's avatar
Michael Yang committed
975

976
977
978
979
	if allowedOrigins := strings.Trim(os.Getenv("OLLAMA_ORIGINS"), "\"'"); allowedOrigins != "" {
		config.AllowOrigins = strings.Split(allowedOrigins, ",")
	}

Michael Yang's avatar
Michael Yang committed
980
981
982
983
984
985
986
987
	for _, allowOrigin := range defaultAllowOrigins {
		config.AllowOrigins = append(config.AllowOrigins,
			fmt.Sprintf("http://%s", allowOrigin),
			fmt.Sprintf("https://%s", allowOrigin),
			fmt.Sprintf("http://%s:*", allowOrigin),
			fmt.Sprintf("https://%s:*", allowOrigin),
		)
	}
Michael Yang's avatar
Michael Yang committed
988

Bruce MacDonald's avatar
Bruce MacDonald committed
989
	r := gin.Default()
990
991
	r.Use(
		cors.New(config),
992
		allowedHostsMiddleware(s.addr),
993
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
994

Daniel Hiltgen's avatar
Daniel Hiltgen committed
995
996
997
998
999
1000
1001
1002
1003
1004
1005
	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)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1006

1007
	// Compatibility endpoints
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1008
	r.POST("/v1/chat/completions", openai.Middleware(), s.ChatHandler)
1009

Michael Yang's avatar
Michael Yang committed
1010
1011
1012
1013
1014
	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
1015
		r.Handle(method, "/api/tags", s.ListModelsHandler)
Michael Yang's avatar
Michael Yang committed
1016
1017
1018
		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
1019
1020
	}

1021
1022
1023
1024
	return r
}

func Serve(ln net.Listener) error {
Michael Yang's avatar
Michael Yang committed
1025
	level := slog.LevelInfo
1026
	if debug := os.Getenv("OLLAMA_DEBUG"); debug != "" {
Michael Yang's avatar
Michael Yang committed
1027
		level = slog.LevelDebug
1028
	}
Michael Yang's avatar
Michael Yang committed
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044

	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))

1045
1046
1047
1048
1049
1050
1051
1052
	blobsDir, err := GetBlobsPath("")
	if err != nil {
		return err
	}
	if err := fixBlobs(blobsDir); err != nil {
		return err
	}

1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
	if noprune := os.Getenv("OLLAMA_NOPRUNE"); noprune == "" {
		// 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
1069
1070
1071
	ctx, done := context.WithCancel(context.Background())
	sched := InitScheduler(ctx)
	s := &Server{addr: ln.Addr(), sched: sched}
1072
1073
	r := s.GenerateRoutes()

1074
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1075
	srvr := &http.Server{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1076
1077
1078
		Handler: r,
	}

1079
1080
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
1081
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
1082
1083
	go func() {
		<-signals
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1084
1085
		done()
		sched.unloadAllRunners()
1086
		gpu.Cleanup()
1087
1088
1089
		os.Exit(0)
	}()

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1090
	if err := llm.Init(); err != nil {
1091
1092
		return fmt.Errorf("unable to initialize llm library %w", err)
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1093
1094
1095
1096
1097
1098

	s.sched.Run(ctx)

	// 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
	_ = gpu.GetGPUInfo()
1099

1100
	return srvr.Serve(ln)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1101
}
Michael Yang's avatar
Michael Yang committed
1102

1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
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
1128
func streamResponse(c *gin.Context, ch chan any) {
1129
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
1130
1131
1132
1133
1134
1135
1136
1137
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

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

1142
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
1143
1144
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
1145
			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1146
1147
1148
1149
1150
1151
			return false
		}

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

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

1159
	prompt, err := ChatPrompt(template, messages, numCtx, encode)
1160
1161
1162
1163
1164
1165
1166
	if err != nil {
		return "", err
	}

	return prompt, nil
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1167
func (s *Server) ChatHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
	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
	}

1191
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
1192
1193
	if err != nil {
		var pErr *fs.PathError
1194
		if errors.As(err, &pErr) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1195
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
1196
1197
1198
1199
1200
1201
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

1202
	if model.IsEmbedding() {
1203
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "embedding models do not support chat"})
1204
1205
1206
		return
	}

1207
1208
1209
	opts, err := modelOptions(model, req.Options)
	if err != nil {
		if errors.Is(err, api.ErrInvalidOpts) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1210
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
1211
			return
Bruce MacDonald's avatar
Bruce MacDonald committed
1212
		}
1213
1214
1215
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
1216
1217
1218

	var sessionDuration time.Duration
	if req.KeepAlive == nil {
1219
		sessionDuration = getDefaultSessionDuration()
1220
1221
1222
1223
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1224
1225
1226
1227
1228
	rCh, eCh := s.sched.GetRunner(c.Request.Context(), model, opts, sessionDuration)
	var runner *runnerRef
	select {
	case runner = <-rCh:
	case err = <-eCh:
1229
1230
1231
1232
1233
		if errors.Is(err, context.Canceled) {
			c.JSON(499, gin.H{"error": "request canceled"})
			return
		}

1234
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
1235
1236
1237
1238
1239
		return
	}

	checkpointLoaded := time.Now()

1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
	// 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
1250
	prompt, err := chatPrompt(c.Request.Context(), runner, model.Template, req.Messages, opts.NumCtx)
Bruce MacDonald's avatar
Bruce MacDonald committed
1251
1252
1253
1254
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
1255

1256
	// an empty request loads the model
1257
	if len(req.Messages) == 0 || prompt == "" {
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
		resp := api.ChatResponse{
			CreatedAt: time.Now().UTC(),
			Model:     req.Model,
			Done:      true,
			Message:   api.Message{Role: "assistant"},
		}
		c.JSON(http.StatusOK, resp)
		return
	}

1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
	// 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))
1286

Bruce MacDonald's avatar
Bruce MacDonald committed
1287
1288
1289
1290
1291
	ch := make(chan any)

	go func() {
		defer close(ch)

1292
		fn := func(r llm.CompletionResponse) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1293
1294

			resp := api.ChatResponse{
1295
				Model:     req.Model,
1296
				CreatedAt: time.Now().UTC(),
1297
				Message:   api.Message{Role: "assistant", Content: r.Content},
Bruce MacDonald's avatar
Bruce MacDonald committed
1298
1299
1300
1301
1302
1303
1304
1305
1306
				Done:      r.Done,
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}

1307
1308
1309
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
Bruce MacDonald's avatar
Bruce MacDonald committed
1310
1311
1312
1313
1314
			}

			ch <- resp
		}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1315
		if err := runner.llama.Completion(c.Request.Context(), llm.CompletionRequest{
1316
1317
			Prompt:  prompt,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
1318
			Images:  images,
1319
			Options: opts,
1320
		}, fn); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1321
1322
1323
1324
1325
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
1326
1327
		// Accumulate responses into the final response
		var final api.ChatResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
1328
1329
		var sb strings.Builder
		for resp := range ch {
1330
1331
			switch r := resp.(type) {
			case api.ChatResponse:
1332
				sb.WriteString(r.Message.Content)
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
				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
1345
1346
			}
		}
1347

1348
		final.Message = api.Message{Role: "assistant", Content: sb.String()}
1349
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
1350
1351
1352
1353
1354
		return
	}

	streamResponse(c, ch)
}