"src/targets/vscode:/vscode.git/clone" did not exist on "a625f7b4361387c6cadd5c5a6687981ab40e112f"
routes.go 31.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
	"strconv"
Michael Yang's avatar
Michael Yang committed
20
	"strings"
21
	"syscall"
22
	"time"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
23

Michael Yang's avatar
Michael Yang committed
24
	"github.com/gin-contrib/cors"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
25
	"github.com/gin-gonic/gin"
26
	"golang.org/x/exp/slices"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
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"
32
	"github.com/ollama/ollama/server/envconfig"
Michael Yang's avatar
Michael Yang committed
33
	"github.com/ollama/ollama/types/model"
34
	"github.com/ollama/ollama/version"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
35
36
)

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

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

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

	gin.SetMode(mode)
}

56
57
var defaultSessionDuration = 5 * time.Minute

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

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

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

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

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

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

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

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

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

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

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

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

	checkpointLoaded := time.Now()

Bruce MacDonald's avatar
Bruce MacDonald committed
168
169
170
171
172
	var prompt string
	switch {
	case req.Raw:
		prompt = req.Prompt
	case req.Prompt != "":
173
174
		if req.Template == "" {
			req.Template = model.Template
Bruce MacDonald's avatar
Bruce MacDonald committed
175
176
		}

177
178
179
180
181
182
183
184
185
		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
186
187
188
189
190
191
192
193
194
195
196
197
198
		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
199
		if req.Context != nil {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
200
			prev, err := runner.llama.Detokenize(c.Request.Context(), req.Context)
Bruce MacDonald's avatar
Bruce MacDonald committed
201
202
203
204
205
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}

206
			sb.WriteString(prev)
207
208
		}

209
210
211
		sb.WriteString(p)

		prompt = sb.String()
Bruce MacDonald's avatar
Bruce MacDonald committed
212
213
	}

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

Bruce MacDonald's avatar
Bruce MacDonald committed
216
	ch := make(chan any)
Bruce MacDonald's avatar
Bruce MacDonald committed
217
	var generated strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
218
219
220
	go func() {
		defer close(ch)

221
		fn := func(r llm.CompletionResponse) {
Bruce MacDonald's avatar
Bruce MacDonald committed
222
223
224
225
			// 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
226
227
			}

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

241
242
243
244
245
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)

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

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

					resp.Context = append(req.Context, tokens...)
Bruce MacDonald's avatar
Bruce MacDonald committed
260
261
262
263
				}
			}

			ch <- resp
Bruce MacDonald's avatar
Bruce MacDonald committed
264
265
		}

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

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

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

		final.Response = sb.String()
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
311
312
313
314
315
316
		return
	}

	streamResponse(c, ch)
}

317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
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
343
func (s *Server) EmbeddingsHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
	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
	}

360
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
361
	if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
362
		var pErr *fs.PathError
363
		if errors.As(err, &pErr) {
Bruce MacDonald's avatar
Bruce MacDonald committed
364
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
365
366
367
368
369
370
371
372
373
			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
374
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
375
			return
Bruce MacDonald's avatar
Bruce MacDonald committed
376
		}
377
378
379
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
380
381
382

	var sessionDuration time.Duration
	if req.KeepAlive == nil {
383
		sessionDuration = getDefaultSessionDuration()
384
385
386
387
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
388
389
390
391
392
	rCh, eCh := s.sched.GetRunner(c.Request.Context(), model, opts, sessionDuration)
	var runner *runnerRef
	select {
	case runner = <-rCh:
	case err = <-eCh:
393
		handleErrorResponse(c, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
394
395
396
		return
	}

397
398
399
	// an empty request loads the model
	if req.Prompt == "" {
		c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: []float64{}})
Bruce MacDonald's avatar
Bruce MacDonald committed
400
401
402
		return
	}

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

Michael Yang's avatar
Michael Yang committed
428
429
430
431
432
433
434
	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"})
435
436
437
		return
	}

438
439
440
	ch := make(chan any)
	go func() {
		defer close(ch)
441
442
		fn := func(r api.ProgressResponse) {
			ch <- r
443
		}
444

Michael Yang's avatar
Michael Yang committed
445
		regOpts := &registryOptions{
446
447
448
			Insecure: req.Insecure,
		}

449
450
451
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
452
		if err := PullModel(ctx, model, regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
453
			ch <- gin.H{"error": err.Error()}
454
455
456
		}
	}()

457
458
459
460
461
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

462
463
464
	streamResponse(c, ch)
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
465
func (s *Server) PushModelHandler(c *gin.Context) {
466
	var req api.PushRequest
Michael Yang's avatar
Michael Yang committed
467
468
469
470
471
472
473
	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
474
475
		return
	}
Michael Yang's avatar
Michael Yang committed
476

Michael Yang's avatar
Michael Yang committed
477
478
479
480
481
482
483
	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"})
484
485
486
		return
	}

487
488
489
	ch := make(chan any)
	go func() {
		defer close(ch)
490
491
		fn := func(r api.ProgressResponse) {
			ch <- r
492
		}
493

Michael Yang's avatar
Michael Yang committed
494
		regOpts := &registryOptions{
495
496
497
			Insecure: req.Insecure,
		}

Michael Yang's avatar
Michael Yang committed
498
499
500
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

Michael Yang's avatar
Michael Yang committed
501
		if err := PushModel(ctx, model, regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
502
			ch <- gin.H{"error": err.Error()}
503
504
505
		}
	}()

506
507
508
509
510
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

511
512
513
	streamResponse(c, ch)
}

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

Michael Yang's avatar
Michael Yang committed
524
525
526
	name := model.ParseName(cmp.Or(req.Model, req.Name))
	if !name.IsValid() {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid model name"})
527
528
529
		return
	}

Michael Yang's avatar
Michael Yang committed
530
531
	if req.Path == "" && req.Modelfile == "" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
Michael Yang's avatar
Michael Yang committed
532
533
		return
	}
Michael Yang's avatar
Michael Yang committed
534

Michael Yang's avatar
Michael Yang committed
535
	var r io.Reader = strings.NewReader(req.Modelfile)
Michael Yang's avatar
Michael Yang committed
536
	if req.Path != "" && req.Modelfile == "" {
Michael Yang's avatar
Michael Yang committed
537
		f, err := os.Open(req.Path)
Michael Yang's avatar
Michael Yang committed
538
539
540
541
		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
542
		defer f.Close()
Michael Yang's avatar
Michael Yang committed
543

Michael Yang's avatar
Michael Yang committed
544
		r = f
Michael Yang's avatar
Michael Yang committed
545
	}
Michael Yang's avatar
Michael Yang committed
546

Michael Yang's avatar
Michael Yang committed
547
	modelfile, err := model.ParseFile(r)
Michael Yang's avatar
Michael Yang committed
548
549
550
551
552
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
553
	ch := make(chan any)
Michael Yang's avatar
Michael Yang committed
554
555
	go func() {
		defer close(ch)
556
557
		fn := func(resp api.ProgressResponse) {
			ch <- resp
558
559
		}

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

Michael Yang's avatar
Michael Yang committed
563
		if err := CreateModel(ctx, name.String(), filepath.Dir(req.Path), req.Quantization, modelfile, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
564
			ch <- gin.H{"error": err.Error()}
565
		}
Michael Yang's avatar
Michael Yang committed
566
	}()
Michael Yang's avatar
Michael Yang committed
567

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

Michael Yang's avatar
Michael Yang committed
573
	streamResponse(c, ch)
Bruce MacDonald's avatar
Bruce MacDonald committed
574
575
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
576
func (s *Server) DeleteModelHandler(c *gin.Context) {
577
	var req api.DeleteRequest
Michael Yang's avatar
Michael Yang committed
578
579
580
581
582
583
584
	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()})
585
586
587
		return
	}

Michael Yang's avatar
Michael Yang committed
588
589
590
591
592
593
594
	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"})
595
596
597
		return
	}

Michael Yang's avatar
Michael Yang committed
598
	if err := DeleteModel(model); err != nil {
599
		if os.IsNotExist(err) {
Michael Yang's avatar
Michael Yang committed
600
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", model)})
601
		} else {
602
603
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
604
605
		return
	}
Michael Yang's avatar
Michael Yang committed
606
607
608
609
610
611
612
613
614
615
616
617

	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
	}

618
	c.JSON(http.StatusOK, nil)
619
620
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
621
func (s *Server) ShowModelHandler(c *gin.Context) {
Patrick Devine's avatar
Patrick Devine committed
622
	var req api.ShowRequest
Michael Yang's avatar
Michael Yang committed
623
624
625
626
627
628
629
	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
630
631
632
		return
	}

Michael Yang's avatar
Michael Yang committed
633
	if req.Model != "" {
Michael Yang's avatar
Michael Yang committed
634
		// noop
Michael Yang's avatar
Michael Yang committed
635
	} else if req.Name != "" {
Michael Yang's avatar
Michael Yang committed
636
		req.Model = req.Name
Michael Yang's avatar
Michael Yang committed
637
	} else {
638
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
639
640
641
		return
	}

642
	resp, err := GetModelInfo(req)
Patrick Devine's avatar
Patrick Devine committed
643
644
	if err != nil {
		if os.IsNotExist(err) {
Michael Yang's avatar
Michael Yang committed
645
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
Patrick Devine's avatar
Patrick Devine committed
646
647
648
649
650
651
652
653
654
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

	c.JSON(http.StatusOK, resp)
}

655
656
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
	model, err := GetModel(req.Model)
Patrick Devine's avatar
Patrick Devine committed
657
658
659
660
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
661
	modelDetails := api.ModelDetails{
662
		ParentModel:       model.ParentModel,
Patrick Devine's avatar
Patrick Devine committed
663
664
665
666
667
668
669
		Format:            model.Config.ModelFormat,
		Family:            model.Config.ModelFamily,
		Families:          model.Config.ModelFamilies,
		ParameterSize:     model.Config.ModelType,
		QuantizationLevel: model.Config.FileType,
	}

670
671
672
673
674
675
676
677
	if req.System != "" {
		model.System = req.System
	}

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

678
679
680
681
682
	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
683
684
685
686
	resp := &api.ShowResponse{
		License:  strings.Join(model.License, "\n"),
		System:   model.System,
		Template: model.Template,
Patrick Devine's avatar
Patrick Devine committed
687
		Details:  modelDetails,
688
		Messages: msgs,
Patrick Devine's avatar
Patrick Devine committed
689
690
691
692
693
694
695
696
	}

	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
697
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
Patrick Devine's avatar
Patrick Devine committed
698
			}
Patrick Devine's avatar
Patrick Devine committed
699
700
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
Patrick Devine's avatar
Patrick Devine committed
701
702
703
704
		}
	}
	resp.Parameters = strings.Join(params, "\n")

705
706
707
708
709
710
	for k, v := range req.Options {
		if _, ok := req.Options[k]; ok {
			model.Options[k] = v
		}
	}

711
712
713
714
	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)
Michael Yang's avatar
Michael Yang committed
715
	fmt.Fprint(&sb, model.String())
716
	resp.Modelfile = sb.String()
717

Patrick Devine's avatar
Patrick Devine committed
718
719
720
	return resp, nil
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
721
func (s *Server) ListModelsHandler(c *gin.Context) {
722
	models := make([]api.ModelResponse, 0)
723
	manifestsPath, err := GetManifestPath()
Patrick Devine's avatar
Patrick Devine committed
724
725
726
727
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
728

Patrick Devine's avatar
Patrick Devine committed
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
	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
744
			Model:   model.ShortName,
Patrick Devine's avatar
Patrick Devine committed
745
746
747
748
749
750
751
			Name:    model.ShortName,
			Size:    model.Size,
			Digest:  model.Digest,
			Details: modelDetails,
		}, nil
	}

Michael Yang's avatar
Michael Yang committed
752
	walkFunc := func(path string, info os.FileInfo, _ error) error {
Patrick Devine's avatar
Patrick Devine committed
753
		if !info.IsDir() {
754
755
756
757
			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), "/")
758

759
			resp, err := modelResponse(canonicalModelPath)
Patrick Devine's avatar
Patrick Devine committed
760
			if err != nil {
761
				slog.Info(fmt.Sprintf("skipping file: %s", canonicalModelPath))
Michael Yang's avatar
Michael Yang committed
762
				// nolint: nilerr
763
				return nil
Patrick Devine's avatar
Patrick Devine committed
764
			}
Michael Yang's avatar
Michael Yang committed
765

Patrick Devine's avatar
Patrick Devine committed
766
767
			resp.ModifiedAt = info.ModTime()
			models = append(models, resp)
Patrick Devine's avatar
Patrick Devine committed
768
		}
Michael Yang's avatar
Michael Yang committed
769

Patrick Devine's avatar
Patrick Devine committed
770
		return nil
Michael Yang's avatar
Michael Yang committed
771
772
	}

773
	if err := filepath.Walk(manifestsPath, walkFunc); err != nil {
Patrick Devine's avatar
Patrick Devine committed
774
775
776
777
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
778
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
779
780
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
781
func (s *Server) CopyModelHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
782
783
	var r api.CopyRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
784
785
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
786
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
787
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Patrick Devine's avatar
Patrick Devine committed
788
789
790
		return
	}

Michael Yang's avatar
Michael Yang committed
791
792
	src := model.ParseName(r.Source)
	if !src.IsValid() {
Michael Yang's avatar
Michael Yang committed
793
794
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("source %q is invalid", r.Source)})
		return
795
796
	}

Michael Yang's avatar
Michael Yang committed
797
798
	dst := model.ParseName(r.Destination)
	if !dst.IsValid() {
Michael Yang's avatar
Michael Yang committed
799
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("destination %q is invalid", r.Source)})
Patrick Devine's avatar
Patrick Devine committed
800
801
		return
	}
Michael Yang's avatar
Michael Yang committed
802
803
804
805
806
807

	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
808
809
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
810
func (s *Server) HeadBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
811
812
813
814
815
816
817
818
819
820
821
	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
822
	c.Status(http.StatusOK)
Michael Yang's avatar
Michael Yang committed
823
824
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
825
func (s *Server) CreateBlobHandler(c *gin.Context) {
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
	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
	}

844
	layer, err := NewLayer(c.Request.Body, "")
Michael Yang's avatar
Michael Yang committed
845
846
847
848
849
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

850
851
	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
852
853
854
		return
	}

855
	if _, err := layer.Commit(); err != nil {
Michael Yang's avatar
Michael Yang committed
856
857
858
859
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
860
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
861
862
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
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
}

884
func allowedHost(host string) bool {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
885
	if host == "" || host == "localhost" {
886
887
888
889
890
891
892
893
		return true
	}

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

	var tlds = []string{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
894
895
896
		"localhost",
		"local",
		"internal",
897
	}
898

Jeffrey Morgan's avatar
Jeffrey Morgan committed
899
	// check if the host is a local TLD
900
901
902
903
904
905
	for _, tld := range tlds {
		if strings.HasSuffix(host, "."+tld) {
			return true
		}
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
906
	return false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
907
}
908

Jeffrey Morgan's avatar
Jeffrey Morgan committed
909
910
911
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
	return func(c *gin.Context) {
		if addr == nil {
912
913
914
915
			c.Next()
			return
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
916
		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
917
918
919
920
921
922
923
924
925
			c.Next()
			return
		}

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
926
		if addr, err := netip.ParseAddr(host); err == nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
927
			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
928
929
930
931
932
				c.Next()
				return
			}
		}

933
934
935
936
937
938
939
		if allowedHost(host) {
			c.Next()
			return
		}

		c.AbortWithStatus(http.StatusForbidden)
	}
940
}
941

942
func (s *Server) GenerateRoutes() http.Handler {
Michael Yang's avatar
Michael Yang committed
943
944
	config := cors.DefaultConfig()
	config.AllowWildcard = true
945
	config.AllowBrowserExtensions = true
946
	config.AllowOrigins = envconfig.AllowOrigins
Michael Yang's avatar
Michael Yang committed
947

Bruce MacDonald's avatar
Bruce MacDonald committed
948
	r := gin.Default()
949
950
	r.Use(
		cors.New(config),
951
		allowedHostsMiddleware(s.addr),
952
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
953

Daniel Hiltgen's avatar
Daniel Hiltgen committed
954
955
956
957
958
959
960
961
962
963
964
	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
965

966
	// Compatibility endpoints
Daniel Hiltgen's avatar
Daniel Hiltgen committed
967
	r.POST("/v1/chat/completions", openai.Middleware(), s.ChatHandler)
968

Michael Yang's avatar
Michael Yang committed
969
970
971
972
973
	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
974
		r.Handle(method, "/api/tags", s.ListModelsHandler)
Michael Yang's avatar
Michael Yang committed
975
976
977
		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
978
979
	}

980
981
982
983
	return r
}

func Serve(ln net.Listener) error {
Michael Yang's avatar
Michael Yang committed
984
	level := slog.LevelInfo
985
	if envconfig.Debug {
Michael Yang's avatar
Michael Yang committed
986
		level = slog.LevelDebug
987
	}
Michael Yang's avatar
Michael Yang committed
988

989
	slog.Info("server config", "env", envconfig.AsMap())
Michael Yang's avatar
Michael Yang committed
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
	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))

1005
1006
1007
1008
1009
1010
1011
1012
	blobsDir, err := GetBlobsPath("")
	if err != nil {
		return err
	}
	if err := fixBlobs(blobsDir); err != nil {
		return err
	}

1013
	if !envconfig.NoPrune {
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
		// 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
1029
1030
1031
	ctx, done := context.WithCancel(context.Background())
	sched := InitScheduler(ctx)
	s := &Server{addr: ln.Addr(), sched: sched}
1032
1033
	r := s.GenerateRoutes()

1034
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1035
	srvr := &http.Server{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1036
1037
1038
		Handler: r,
	}

1039
1040
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
1041
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
1042
1043
	go func() {
		<-signals
1044
		srvr.Close()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1045
1046
		done()
		sched.unloadAllRunners()
1047
		gpu.Cleanup()
1048
1049
1050
		os.Exit(0)
	}()

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1051
	if err := llm.Init(); err != nil {
1052
1053
		return fmt.Errorf("unable to initialize llm library %w", err)
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1054
1055
1056
1057
1058
1059

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

1061
	return srvr.Serve(ln)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1062
}
Michael Yang's avatar
Michael Yang committed
1063

1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
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
1089
func streamResponse(c *gin.Context, ch chan any) {
1090
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
1091
1092
1093
1094
1095
1096
1097
1098
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

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

1103
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
1104
1105
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
1106
			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1107
1108
1109
1110
1111
1112
			return false
		}

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

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

1120
	prompt, err := ChatPrompt(template, messages, numCtx, encode)
1121
1122
1123
1124
1125
1126
1127
	if err != nil {
		return "", err
	}

	return prompt, nil
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1128
func (s *Server) ChatHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
	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
	}

1152
	model, err := GetModel(req.Model)
Bruce MacDonald's avatar
Bruce MacDonald committed
1153
1154
	if err != nil {
		var pErr *fs.PathError
1155
		if errors.As(err, &pErr) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1156
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
1157
1158
1159
1160
1161
1162
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

1163
	if model.IsEmbedding() {
1164
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "embedding models do not support chat"})
1165
1166
1167
		return
	}

1168
1169
1170
	opts, err := modelOptions(model, req.Options)
	if err != nil {
		if errors.Is(err, api.ErrInvalidOpts) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1171
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
1172
			return
Bruce MacDonald's avatar
Bruce MacDonald committed
1173
		}
1174
1175
1176
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
1177
1178
1179

	var sessionDuration time.Duration
	if req.KeepAlive == nil {
1180
		sessionDuration = getDefaultSessionDuration()
1181
1182
1183
1184
	} else {
		sessionDuration = req.KeepAlive.Duration
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1185
1186
1187
1188
1189
	rCh, eCh := s.sched.GetRunner(c.Request.Context(), model, opts, sessionDuration)
	var runner *runnerRef
	select {
	case runner = <-rCh:
	case err = <-eCh:
1190
		handleErrorResponse(c, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
1191
1192
1193
1194
1195
		return
	}

	checkpointLoaded := time.Now()

1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
	// 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
1206
	prompt, err := chatPrompt(c.Request.Context(), runner, model.Template, req.Messages, opts.NumCtx)
Bruce MacDonald's avatar
Bruce MacDonald committed
1207
1208
1209
1210
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
1211

1212
	// an empty request loads the model
1213
	if len(req.Messages) == 0 || prompt == "" {
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
		resp := api.ChatResponse{
			CreatedAt: time.Now().UTC(),
			Model:     req.Model,
			Done:      true,
			Message:   api.Message{Role: "assistant"},
		}
		c.JSON(http.StatusOK, resp)
		return
	}

1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
	// 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))
1242

Bruce MacDonald's avatar
Bruce MacDonald committed
1243
1244
1245
1246
1247
	ch := make(chan any)

	go func() {
		defer close(ch)

1248
		fn := func(r llm.CompletionResponse) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1249
1250

			resp := api.ChatResponse{
1251
				Model:     req.Model,
1252
				CreatedAt: time.Now().UTC(),
1253
				Message:   api.Message{Role: "assistant", Content: r.Content},
Bruce MacDonald's avatar
Bruce MacDonald committed
1254
1255
1256
1257
1258
1259
1260
1261
1262
				Done:      r.Done,
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}

1263
1264
1265
			if r.Done {
				resp.TotalDuration = time.Since(checkpointStart)
				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
Bruce MacDonald's avatar
Bruce MacDonald committed
1266
1267
1268
1269
1270
			}

			ch <- resp
		}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1271
		if err := runner.llama.Completion(c.Request.Context(), llm.CompletionRequest{
1272
1273
			Prompt:  prompt,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
1274
			Images:  images,
1275
			Options: opts,
1276
		}, fn); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1277
1278
1279
1280
1281
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
1282
1283
		// Accumulate responses into the final response
		var final api.ChatResponse
Bruce MacDonald's avatar
Bruce MacDonald committed
1284
1285
		var sb strings.Builder
		for resp := range ch {
1286
1287
			switch r := resp.(type) {
			case api.ChatResponse:
1288
				sb.WriteString(r.Message.Content)
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
				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
1301
1302
			}
		}
1303

1304
		final.Message = api.Message{Role: "assistant", Content: sb.String()}
1305
		c.JSON(http.StatusOK, final)
Bruce MacDonald's avatar
Bruce MacDonald committed
1306
1307
1308
1309
1310
		return
	}

	streamResponse(c, ch)
}
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322

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