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

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

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

30
	"github.com/ollama/ollama/api"
31
	"github.com/ollama/ollama/discover"
32
	"github.com/ollama/ollama/envconfig"
Michael Yang's avatar
Michael Yang committed
33
	"github.com/ollama/ollama/fs/ggml"
34
	"github.com/ollama/ollama/llm"
35
	"github.com/ollama/ollama/logutil"
36
	"github.com/ollama/ollama/openai"
37
38
	"github.com/ollama/ollama/server/internal/client/ollama"
	"github.com/ollama/ollama/server/internal/registry"
Michael Yang's avatar
Michael Yang committed
39
	"github.com/ollama/ollama/template"
40
	"github.com/ollama/ollama/thinking"
41
	"github.com/ollama/ollama/tools"
42
	"github.com/ollama/ollama/types/errtypes"
Michael Yang's avatar
Michael Yang committed
43
	"github.com/ollama/ollama/types/model"
44
	"github.com/ollama/ollama/version"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
45
46
)

47
48
49
50
51
52
func experimentEnabled(name string) bool {
	return slices.Contains(strings.Split(os.Getenv("OLLAMA_EXPERIMENT"), ","), name)
}

var useClient2 = experimentEnabled("client2")

Michael Yang's avatar
Michael Yang committed
53
54
var mode string = gin.DebugMode

55
type Server struct {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
56
57
	addr  net.Addr
	sched *Scheduler
58
59
}

Michael Yang's avatar
Michael Yang committed
60
61
62
63
64
65
66
67
68
69
70
71
func init() {
	switch mode {
	case gin.DebugMode:
	case gin.ReleaseMode:
	case gin.TestMode:
	default:
		mode = gin.DebugMode
	}

	gin.SetMode(mode)
}

Michael Yang's avatar
lint  
Michael Yang committed
72
73
74
75
var (
	errRequired    = errors.New("is required")
	errBadTemplate = errors.New("template error")
)
Michael Yang's avatar
Michael Yang committed
76

77
func modelOptions(model *Model, requestOpts map[string]any) (api.Options, error) {
78
79
80
81
82
83
84
85
86
87
	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
88
89
}

Michael Yang's avatar
Michael Yang committed
90
91
// scheduleRunner schedules a runner after validating inputs such as capabilities and model options.
// It returns the allocated runner, model instance, and consolidated options if successful and error otherwise.
92
func (s *Server) scheduleRunner(ctx context.Context, name string, caps []model.Capability, requestOpts map[string]any, keepAlive *api.Duration) (llm.LlamaServer, *Model, *api.Options, error) {
Michael Yang's avatar
Michael Yang committed
93
	if name == "" {
Michael Yang's avatar
Michael Yang committed
94
		return nil, nil, nil, fmt.Errorf("model %w", errRequired)
Bruce MacDonald's avatar
Bruce MacDonald committed
95
96
	}

Michael Yang's avatar
Michael Yang committed
97
	model, err := GetModel(name)
Bruce MacDonald's avatar
Bruce MacDonald committed
98
	if err != nil {
Michael Yang's avatar
Michael Yang committed
99
		return nil, nil, nil, err
100
101
	}

102
103
104
105
	if slices.Contains(model.Config.ModelFamilies, "mllama") && len(model.ProjectorPaths) > 0 {
		return nil, nil, nil, fmt.Errorf("'llama3.2-vision' is no longer compatible with your version of Ollama and has been replaced by a newer version. To re-download, run 'ollama pull llama3.2-vision'")
	}

Michael Yang's avatar
Michael Yang committed
106
	if err := model.CheckCapabilities(caps...); err != nil {
Michael Yang's avatar
Michael Yang committed
107
		return nil, nil, nil, fmt.Errorf("%s %w", name, err)
108
109
	}

Michael Yang's avatar
Michael Yang committed
110
	opts, err := modelOptions(model, requestOpts)
111
	if err != nil {
Michael Yang's avatar
Michael Yang committed
112
		return nil, nil, nil, err
113
114
	}

Michael Yang's avatar
Michael Yang committed
115
	runnerCh, errCh := s.sched.GetRunner(ctx, model, opts, keepAlive)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
116
117
	var runner *runnerRef
	select {
Michael Yang's avatar
Michael Yang committed
118
119
	case runner = <-runnerCh:
	case err = <-errCh:
Michael Yang's avatar
Michael Yang committed
120
		return nil, nil, nil, err
Bruce MacDonald's avatar
Bruce MacDonald committed
121
122
	}

Michael Yang's avatar
Michael Yang committed
123
	return runner.llama, model, &opts, nil
Michael Yang's avatar
Michael Yang committed
124
125
126
}

func (s *Server) GenerateHandler(c *gin.Context) {
127
	checkpointStart := time.Now()
Michael Yang's avatar
Michael Yang committed
128
129
130
131
132
133
	var req api.GenerateRequest
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	} else if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Bruce MacDonald's avatar
Bruce MacDonald committed
134
135
136
		return
	}

137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
	name := model.ParseName(req.Model)
	if !name.IsValid() {
		// Ideally this is "invalid model name" but we're keeping with
		// what the API currently returns until we can change it.
		c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
		return
	}

	// We cannot currently consolidate this into GetModel because all we'll
	// induce infinite recursion given the current code structure.
	name, err := getExistingName(name)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
		return
	}

153
	m, err := GetModel(name.String())
154
155
	if err != nil {
		switch {
156
		case errors.Is(err, fs.ErrNotExist):
157
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
158
		case err.Error() == errtypes.InvalidModelNameErrMsg:
159
160
161
162
163
164
165
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

Patrick Devine's avatar
Patrick Devine committed
166
167
	// expire the runner
	if req.Prompt == "" && req.KeepAlive != nil && int(req.KeepAlive.Seconds()) == 0 {
168
		s.sched.expireRunner(m)
Patrick Devine's avatar
Patrick Devine committed
169
170
171
172
173
174
175
176
177
178
179

		c.JSON(http.StatusOK, api.GenerateResponse{
			Model:      req.Model,
			CreatedAt:  time.Now().UTC(),
			Response:   "",
			Done:       true,
			DoneReason: "unload",
		})
		return
	}

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

185
	caps := []model.Capability{model.CapabilityCompletion}
186
	if req.Suffix != "" {
187
		caps = append(caps, model.CapabilityInsert)
188
	}
189
190
191
192
193
194
195
	if req.Think != nil && *req.Think {
		caps = append(caps, model.CapabilityThinking)
		// TODO(drifkin): consider adding a warning if it's false and the model
		// doesn't support thinking. It's not strictly required, but it can be a
		// hint that the user is on an older qwen3/r1 model that doesn't have an
		// updated template supporting thinking
	}
196

197
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), caps, req.Options, req.KeepAlive)
Michael Yang's avatar
Michael Yang committed
198
199
200
201
	if errors.Is(err, errCapabilityCompletion) {
		c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("%q does not support generate", req.Model)})
		return
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
202
203
204
205
		handleScheduleError(c, req.Model, err)
		return
	}

206
207
	checkpointLoaded := time.Now()

208
	// load the model
Michael Yang's avatar
Michael Yang committed
209
210
211
212
213
214
215
	if req.Prompt == "" {
		c.JSON(http.StatusOK, api.GenerateResponse{
			Model:      req.Model,
			CreatedAt:  time.Now().UTC(),
			Done:       true,
			DoneReason: "load",
		})
Michael Yang's avatar
Michael Yang committed
216
217
		return
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
218

219
220
	if slices.Contains(m.Config.ModelFamilies, "mllama") && len(req.Images) > 1 {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "this model only supports one image while more than one image requested"})
221
222
223
		return
	}

Michael Yang's avatar
Michael Yang committed
224
225
	images := make([]llm.ImageData, len(req.Images))
	for i := range req.Images {
226
		images[i] = llm.ImageData{ID: i, Data: req.Images[i]}
Michael Yang's avatar
Michael Yang committed
227
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
228

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

240
241
242
243
244
245
246
247
248
249
250
251
		var values template.Values
		if req.Suffix != "" {
			values.Prompt = prompt
			values.Suffix = req.Suffix
		} else {
			var msgs []api.Message
			if req.System != "" {
				msgs = append(msgs, api.Message{Role: "system", Content: req.System})
			} else if m.System != "" {
				msgs = append(msgs, api.Message{Role: "system", Content: m.System})
			}

Michael Yang's avatar
Michael Yang committed
252
253
254
255
			if req.Context == nil {
				msgs = append(msgs, m.Messages...)
			}

256
			for _, i := range images {
257
258
				imgPrompt := ""
				msgs = append(msgs, api.Message{Role: "user", Content: fmt.Sprintf("[img-%d]"+imgPrompt, i.ID)})
259
260
261
262
263
			}

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

264
265
266
		values.Think = req.Think != nil && *req.Think
		values.IsThinkSet = req.Think != nil

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

		if err := tmpl.Execute(&b, values); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		prompt = b.String()
Bruce MacDonald's avatar
Bruce MacDonald committed
284
285
	}

286
287
	var thinkingState *thinking.Parser
	openingTag, closingTag := thinking.InferTags(m.Template.Template)
288
	if req.Think != nil && *req.Think && openingTag != "" && closingTag != "" {
289
		thinkingState = &thinking.Parser{
Devon Rifkin's avatar
Devon Rifkin committed
290
291
			OpeningTag: openingTag,
			ClosingTag: closingTag,
292
293
294
		}
	}

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

319
			if thinkingState != nil {
Devon Rifkin's avatar
Devon Rifkin committed
320
				thinking, content := thinkingState.AddContent(cr.Content)
321
322
323
324
				res.Thinking = thinking
				res.Response = content
			}

325
326
327
328
329
			if _, err := sb.WriteString(cr.Content); err != nil {
				ch <- gin.H{"error": err.Error()}
			}

			if cr.Done {
330
				res.DoneReason = cr.DoneReason.String()
331
332
333
334
				res.TotalDuration = time.Since(checkpointStart)
				res.LoadDuration = checkpointLoaded.Sub(checkpointStart)

				if !req.Raw {
335
					tokens, err := r.Tokenize(c.Request.Context(), prompt+sb.String())
336
337
338
339
					if err != nil {
						ch <- gin.H{"error": err.Error()}
						return
					}
340
					res.Context = tokens
341
342
343
344
				}
			}

			ch <- res
Michael Yang's avatar
Michael Yang committed
345
		}); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
346
347
348
349
350
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
Michael Yang's avatar
Michael Yang committed
351
		var r api.GenerateResponse
352
353
		var sbThinking strings.Builder
		var sbContent strings.Builder
Michael Yang's avatar
Michael Yang committed
354
355
		for rr := range ch {
			switch t := rr.(type) {
356
			case api.GenerateResponse:
357
358
				sbThinking.WriteString(t.Thinking)
				sbContent.WriteString(t.Response)
Michael Yang's avatar
Michael Yang committed
359
				r = t
360
			case gin.H:
Michael Yang's avatar
Michael Yang committed
361
362
363
				msg, ok := t["error"].(string)
				if !ok {
					msg = "unexpected error format in response"
364
				}
Michael Yang's avatar
Michael Yang committed
365
366
367

				c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
				return
368
			default:
Michael Yang's avatar
Michael Yang committed
369
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
Bruce MacDonald's avatar
Bruce MacDonald committed
370
371
372
				return
			}
		}
373

374
375
376
		r.Thinking = sbThinking.String()
		r.Response = sbContent.String()

Michael Yang's avatar
Michael Yang committed
377
		c.JSON(http.StatusOK, r)
Bruce MacDonald's avatar
Bruce MacDonald committed
378
379
380
381
382
383
		return
	}

	streamResponse(c, ch)
}

384
func (s *Server) EmbedHandler(c *gin.Context) {
385
	checkpointStart := time.Now()
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
	var req api.EmbedRequest
	err := c.ShouldBindJSON(&req)
	switch {
	case errors.Is(err, io.EOF):
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	case err != nil:
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	truncate := true

	if req.Truncate != nil && !*req.Truncate {
		truncate = false
	}

	var input []string

	switch i := req.Input.(type) {
	case string:
		if len(i) > 0 {
			input = append(input, i)
		}
	case []any:
		for _, v := range i {
			if _, ok := v.(string); !ok {
				c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid input type"})
				return
			}
			input = append(input, v.(string))
		}
	default:
419
420
421
422
		if req.Input != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid input type"})
			return
		}
423
424
	}

425
426
427
428
429
430
	name, err := getExistingName(model.ParseName(req.Model))
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
		return
	}

431
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), []model.Capability{}, req.Options, req.KeepAlive)
432
433
434
435
436
	if err != nil {
		handleScheduleError(c, req.Model, err)
		return
	}

437
438
	checkpointLoaded := time.Now()

439
440
441
442
443
	if len(input) == 0 {
		c.JSON(http.StatusOK, api.EmbedResponse{Model: req.Model, Embeddings: [][]float32{}})
		return
	}

444
	kvData, _, err := getModelData(m.ModelPath, false)
445
446
447
448
449
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

450
	var count int
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
	for i, s := range input {
		tokens, err := r.Tokenize(c.Request.Context(), s)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		ctxLen := min(opts.NumCtx, int(kvData.ContextLength()))
		if len(tokens) > ctxLen {
			if !truncate {
				c.JSON(http.StatusBadRequest, gin.H{"error": "input length exceeds maximum context length"})
				return
			}

			tokens = tokens[:ctxLen]
			s, err = r.Detokenize(c.Request.Context(), tokens)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}

473
474
		count += len(tokens)

475
476
		input[i] = s
	}
477
478
479
480
481
482
483
484
485
486
487
488

	var g errgroup.Group
	embeddings := make([][]float32, len(input))
	for i, text := range input {
		g.Go(func() error {
			embedding, err := r.Embedding(c.Request.Context(), text)
			if err != nil {
				return err
			}
			embeddings[i] = normalize(embedding)
			return nil
		})
489
490
	}

491
	if err := g.Wait(); err != nil {
492
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": strings.TrimSpace(err.Error())})
493
		return
494
495
496
	}

	resp := api.EmbedResponse{
497
		Model:           req.Model,
498
		Embeddings:      embeddings,
499
500
		TotalDuration:   time.Since(checkpointStart),
		LoadDuration:    checkpointLoaded.Sub(checkpointStart),
501
		PromptEvalCount: count,
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
	}
	c.JSON(http.StatusOK, resp)
}

func normalize(vec []float32) []float32 {
	var sum float32
	for _, v := range vec {
		sum += v * v
	}

	norm := float32(0.0)
	if sum > 0 {
		norm = float32(1.0 / math.Sqrt(float64(sum)))
	}

	for i := range vec {
		vec[i] *= norm
	}
	return vec
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
523
func (s *Server) EmbeddingsHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
524
	var req api.EmbeddingRequest
Michael Yang's avatar
Michael Yang committed
525
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
Bruce MacDonald's avatar
Bruce MacDonald committed
526
527
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
528
	} else if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
529
530
531
532
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

533
534
535
536
537
538
	name := model.ParseName(req.Model)
	if !name.IsValid() {
		c.JSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
	}

539
	r, _, _, err := s.scheduleRunner(c.Request.Context(), name.String(), []model.Capability{}, req.Options, req.KeepAlive)
Bruce MacDonald's avatar
Bruce MacDonald committed
540
	if err != nil {
Michael Yang's avatar
Michael Yang committed
541
		handleScheduleError(c, req.Model, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
542
543
544
		return
	}

545
546
547
	// an empty request loads the model
	if req.Prompt == "" {
		c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: []float64{}})
Bruce MacDonald's avatar
Bruce MacDonald committed
548
549
550
		return
	}

551
	embedding, err := r.Embedding(c.Request.Context(), req.Prompt)
Bruce MacDonald's avatar
Bruce MacDonald committed
552
	if err != nil {
553
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": strings.TrimSpace(err.Error())})
Bruce MacDonald's avatar
Bruce MacDonald committed
554
555
556
		return
	}

557
558
559
	var e []float64
	for _, v := range embedding {
		e = append(e, float64(v))
560
561
562
	}

	resp := api.EmbeddingResponse{
563
		Embedding: e,
564
565
	}
	c.JSON(http.StatusOK, resp)
Bruce MacDonald's avatar
Bruce MacDonald committed
566
567
}

568
func (s *Server) PullHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
569
	var req api.PullRequest
Michael Yang's avatar
Michael Yang committed
570
571
572
573
574
575
576
	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
577
578
579
		return
	}

580
581
	name := model.ParseName(cmp.Or(req.Model, req.Name))
	if !name.IsValid() {
582
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": errtypes.InvalidModelNameErrMsg})
583
584
585
		return
	}

586
587
	name, err = getExistingName(name)
	if err != nil {
588
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
589
590
591
		return
	}

592
593
594
	ch := make(chan any)
	go func() {
		defer close(ch)
595
596
		fn := func(r api.ProgressResponse) {
			ch <- r
597
		}
598

Michael Yang's avatar
Michael Yang committed
599
		regOpts := &registryOptions{
600
601
602
			Insecure: req.Insecure,
		}

603
604
605
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

606
		if err := PullModel(ctx, name.DisplayShortest(), regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
607
			ch <- gin.H{"error": err.Error()}
608
609
610
		}
	}()

611
612
613
614
615
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

616
617
618
	streamResponse(c, ch)
}

619
func (s *Server) PushHandler(c *gin.Context) {
620
	var req api.PushRequest
Michael Yang's avatar
Michael Yang committed
621
622
623
624
625
626
627
	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
628
629
		return
	}
Michael Yang's avatar
Michael Yang committed
630

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

641
642
643
	ch := make(chan any)
	go func() {
		defer close(ch)
644
645
		fn := func(r api.ProgressResponse) {
			ch <- r
646
		}
647

Michael Yang's avatar
Michael Yang committed
648
		regOpts := &registryOptions{
649
650
651
			Insecure: req.Insecure,
		}

Michael Yang's avatar
Michael Yang committed
652
653
654
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

655
656
657
658
659
660
661
		name, err := getExistingName(model.ParseName(mname))
		if err != nil {
			ch <- gin.H{"error": err.Error()}
			return
		}

		if err := PushModel(ctx, name.DisplayShortest(), regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
662
			ch <- gin.H{"error": err.Error()}
663
664
665
		}
	}()

666
667
668
669
670
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

671
672
673
	streamResponse(c, ch)
}

674
675
676
677
// getExistingName searches the models directory for the longest prefix match of
// the input name and returns the input name with all existing parts replaced
// with each part found. If no parts are found, the input name is returned as
// is.
678
679
680
func getExistingName(n model.Name) (model.Name, error) {
	var zero model.Name
	existing, err := Manifests(true)
681
	if err != nil {
682
		return zero, err
683
	}
684
	var set model.Name // tracks parts already canonicalized
685
	for e := range existing {
686
687
688
689
690
691
692
693
694
695
696
		if set.Host == "" && strings.EqualFold(e.Host, n.Host) {
			n.Host = e.Host
		}
		if set.Namespace == "" && strings.EqualFold(e.Namespace, n.Namespace) {
			n.Namespace = e.Namespace
		}
		if set.Model == "" && strings.EqualFold(e.Model, n.Model) {
			n.Model = e.Model
		}
		if set.Tag == "" && strings.EqualFold(e.Tag, n.Tag) {
			n.Tag = e.Tag
697
698
		}
	}
699
	return n, nil
700
701
}

702
func (s *Server) DeleteHandler(c *gin.Context) {
703
704
	var r api.DeleteRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
705
706
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
707
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
708
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
709
710
711
		return
	}

712
713
714
	n := model.ParseName(cmp.Or(r.Model, r.Name))
	if !n.IsValid() {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("name %q is invalid", cmp.Or(r.Model, r.Name))})
715
716
		return
	}
Michael Yang's avatar
Michael Yang committed
717

718
719
720
721
722
723
	n, err := getExistingName(n)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", cmp.Or(r.Model, r.Name))})
		return
	}

724
	m, err := ParseNamedManifest(n)
Michael Yang's avatar
Michael Yang committed
725
	if err != nil {
726
727
728
729
730
731
		switch {
		case os.IsNotExist(err):
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", cmp.Or(r.Model, r.Name))})
		default:
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
Michael Yang's avatar
Michael Yang committed
732
733
734
		return
	}

735
	if err := m.Remove(); err != nil {
Michael Yang's avatar
Michael Yang committed
736
737
738
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
739
740
741
742
743

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

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

Michael Yang's avatar
Michael Yang committed
758
	if req.Model != "" {
Michael Yang's avatar
Michael Yang committed
759
		// noop
Michael Yang's avatar
Michael Yang committed
760
	} else if req.Name != "" {
Michael Yang's avatar
Michael Yang committed
761
		req.Model = req.Name
Michael Yang's avatar
Michael Yang committed
762
	} else {
763
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
764
765
766
		return
	}

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

	c.JSON(http.StatusOK, resp)
}

783
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
784
785
	name := model.ParseName(req.Model)
	if !name.IsValid() {
CYJiang's avatar
CYJiang committed
786
		return nil, ErrModelPathInvalid
787
788
789
790
791
792
793
	}
	name, err := getExistingName(name)
	if err != nil {
		return nil, err
	}

	m, err := GetModel(name.String())
Patrick Devine's avatar
Patrick Devine committed
794
795
796
797
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
798
	modelDetails := api.ModelDetails{
799
800
801
802
803
804
		ParentModel:       m.ParentModel,
		Format:            m.Config.ModelFormat,
		Family:            m.Config.ModelFamily,
		Families:          m.Config.ModelFamilies,
		ParameterSize:     m.Config.ModelType,
		QuantizationLevel: m.Config.FileType,
Patrick Devine's avatar
Patrick Devine committed
805
806
	}

807
	if req.System != "" {
808
		m.System = req.System
809
810
	}

Michael Yang's avatar
Michael Yang committed
811
812
813
	msgs := make([]api.Message, len(m.Messages))
	for i, msg := range m.Messages {
		msgs[i] = api.Message{Role: msg.Role, Content: msg.Content}
814
815
	}

816
	manifest, err := ParseNamedManifest(name)
817
818
819
820
	if err != nil {
		return nil, err
	}

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

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

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

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

858
	kvData, tensors, err := getModelData(m.ModelPath, req.Verbose)
859
860
861
	if err != nil {
		return nil, err
	}
862

863
864
865
866
	delete(kvData, "general.name")
	delete(kvData, "tokenizer.chat_template")
	resp.ModelInfo = kvData

867
868
869
870
871
872
	tensorData := make([]api.Tensor, len(tensors.Items()))
	for cnt, t := range tensors.Items() {
		tensorData[cnt] = api.Tensor{Name: t.Name, Type: t.Type(), Shape: t.Shape}
	}
	resp.Tensors = tensorData

873
	if len(m.ProjectorPaths) > 0 {
874
		projectorData, _, err := getModelData(m.ProjectorPaths[0], req.Verbose)
875
876
877
878
879
880
		if err != nil {
			return nil, err
		}
		resp.ProjectorInfo = projectorData
	}

Patrick Devine's avatar
Patrick Devine committed
881
882
883
	return resp, nil
}

884
func getModelData(digest string, verbose bool) (ggml.KV, ggml.Tensors, error) {
885
886
887
888
	maxArraySize := 0
	if verbose {
		maxArraySize = -1
	}
889
	data, err := llm.LoadModel(digest, maxArraySize)
890
	if err != nil {
891
		return nil, ggml.Tensors{}, err
892
893
	}

894
	kv := data.KV()
895
896
897
898
899
900
901
902
903

	if !verbose {
		for k := range kv {
			if t, ok := kv[k].([]any); len(t) > 5 && ok {
				kv[k] = []any{}
			}
		}
	}

904
	return kv, data.Tensors(), nil
905
906
}

907
func (s *Server) ListHandler(c *gin.Context) {
908
	ms, err := Manifests(true)
Patrick Devine's avatar
Patrick Devine committed
909
910
911
912
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
913

914
	models := []api.ListModelResponse{}
915
916
	for n, m := range ms {
		var cf ConfigV2
917
918
919
920
921
922
923
924
925
926
927
928
929

		if m.Config.Digest != "" {
			f, err := m.Config.Open()
			if err != nil {
				slog.Warn("bad manifest filepath", "name", n, "error", err)
				continue
			}
			defer f.Close()

			if err := json.NewDecoder(f).Decode(&cf); err != nil {
				slog.Warn("bad manifest config", "name", n, "error", err)
				continue
			}
Patrick Devine's avatar
Patrick Devine committed
930
		}
Michael Yang's avatar
Michael Yang committed
931

932
		r := api.ListModelResponse{
933
934
935
936
937
938
939
940
941
942
943
944
			Model:      n.DisplayShortest(),
			Name:       n.DisplayShortest(),
			Size:       m.Size(),
			Digest:     m.digest,
			ModifiedAt: m.fi.ModTime(),
			Details: api.ModelDetails{
				Format:            cf.ModelFormat,
				Family:            cf.ModelFamily,
				Families:          cf.ModelFamilies,
				ParameterSize:     cf.ModelType,
				QuantizationLevel: cf.FileType,
			},
945
946
947
948
949
950
951
952
953
954
		}

		model, err := GetModel(n.String())
		if err != nil {
			slog.Warn("bad model details", "name", n, "error", err)
		} else {
			r.Capabilities = model.Capabilities()
		}

		models = append(models, r)
Patrick Devine's avatar
Patrick Devine committed
955
956
	}

957
	slices.SortStableFunc(models, func(i, j api.ListModelResponse) int {
958
959
960
961
		// most recently modified first
		return cmp.Compare(j.ModifiedAt.Unix(), i.ModifiedAt.Unix())
	})

Michael Yang's avatar
Michael Yang committed
962
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
963
964
}

965
func (s *Server) CopyHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
966
967
	var r api.CopyRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
968
969
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
970
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
971
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Patrick Devine's avatar
Patrick Devine committed
972
973
974
		return
	}

Michael Yang's avatar
Michael Yang committed
975
976
	src := model.ParseName(r.Source)
	if !src.IsValid() {
Michael Yang's avatar
Michael Yang committed
977
978
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("source %q is invalid", r.Source)})
		return
979
	}
980
981
982
983
984
	src, err := getExistingName(src)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
985

Michael Yang's avatar
Michael Yang committed
986
987
	dst := model.ParseName(r.Destination)
	if !dst.IsValid() {
988
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("destination %q is invalid", r.Destination)})
Patrick Devine's avatar
Patrick Devine committed
989
990
		return
	}
991
992
	dst, err = getExistingName(dst)
	if err != nil {
993
994
995
996
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
997
998
999
1000
1001
	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
1002
1003
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1004
func (s *Server) HeadBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
	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
1016
	c.Status(http.StatusOK)
Michael Yang's avatar
Michael Yang committed
1017
1018
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1019
func (s *Server) CreateBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1020
1021
	if ib, ok := intermediateBlobs[c.Param("digest")]; ok {
		p, err := GetBlobsPath(ib)
1022
1023
1024
1025
1026
1027
		if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		if _, err := os.Stat(p); errors.Is(err, os.ErrNotExist) {
Michael Yang's avatar
Michael Yang committed
1028
1029
			slog.Info("evicting intermediate blob which no longer exists", "digest", ib)
			delete(intermediateBlobs, c.Param("digest"))
1030
1031
1032
1033
1034
1035
1036
1037
1038
		} else if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		} else {
			c.Status(http.StatusOK)
			return
		}
	}

1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
	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
	}

1057
	layer, err := NewLayer(c.Request.Body, "")
Michael Yang's avatar
Michael Yang committed
1058
1059
1060
1061
1062
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

1063
1064
	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
1065
1066
1067
		return
	}

Michael Yang's avatar
Michael Yang committed
1068
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
1069
1070
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
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
}

1092
func allowedHost(host string) bool {
1093
1094
	host = strings.ToLower(host)

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1095
	if host == "" || host == "localhost" {
1096
1097
1098
		return true
	}

1099
	if hostname, err := os.Hostname(); err == nil && host == strings.ToLower(hostname) {
1100
1101
1102
		return true
	}

Michael Yang's avatar
lint  
Michael Yang committed
1103
	tlds := []string{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1104
1105
1106
		"localhost",
		"local",
		"internal",
1107
	}
1108

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1109
	// check if the host is a local TLD
1110
1111
1112
1113
1114
1115
	for _, tld := range tlds {
		if strings.HasSuffix(host, "."+tld) {
			return true
		}
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1116
	return false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1117
}
1118

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1119
1120
1121
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
	return func(c *gin.Context) {
		if addr == nil {
1122
1123
1124
1125
			c.Next()
			return
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1126
		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
1127
1128
1129
1130
1131
1132
1133
1134
1135
			c.Next()
			return
		}

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1136
		if addr, err := netip.ParseAddr(host); err == nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1137
			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1138
1139
1140
1141
1142
				c.Next()
				return
			}
		}

1143
		if allowedHost(host) {
Michael Yang's avatar
lint  
Michael Yang committed
1144
			if c.Request.Method == http.MethodOptions {
1145
1146
1147
1148
				c.AbortWithStatus(http.StatusNoContent)
				return
			}

1149
1150
1151
1152
1153
1154
			c.Next()
			return
		}

		c.AbortWithStatus(http.StatusForbidden)
	}
1155
}
1156

1157
func (s *Server) GenerateRoutes(rc *ollama.Registry) (http.Handler, error) {
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
	corsConfig := cors.DefaultConfig()
	corsConfig.AllowWildcard = true
	corsConfig.AllowBrowserExtensions = true
	corsConfig.AllowHeaders = []string{
		"Authorization",
		"Content-Type",
		"User-Agent",
		"Accept",
		"X-Requested-With",

		// OpenAI compatibility headers
1169
1170
1171
1172
1173
		"OpenAI-Beta",
		"x-stainless-arch",
		"x-stainless-async",
		"x-stainless-custom-poll-interval",
		"x-stainless-helper-method",
1174
1175
		"x-stainless-lang",
		"x-stainless-os",
1176
1177
		"x-stainless-package-version",
		"x-stainless-poll-helper",
1178
1179
1180
1181
1182
1183
		"x-stainless-retry-count",
		"x-stainless-runtime",
		"x-stainless-runtime-version",
		"x-stainless-timeout",
	}
	corsConfig.AllowOrigins = envconfig.AllowedOrigins()
Michael Yang's avatar
Michael Yang committed
1184

Bruce MacDonald's avatar
Bruce MacDonald committed
1185
	r := gin.Default()
1186
	r.HandleMethodNotAllowed = true
1187
	r.Use(
1188
		cors.New(corsConfig),
1189
		allowedHostsMiddleware(s.addr),
1190
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
1191

1192
1193
1194
1195
1196
1197
	// General
	r.HEAD("/", func(c *gin.Context) { c.String(http.StatusOK, "Ollama is running") })
	r.GET("/", func(c *gin.Context) { c.String(http.StatusOK, "Ollama is running") })
	r.HEAD("/api/version", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"version": version.Version}) })
	r.GET("/api/version", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"version": version.Version}) })

1198
	// Local model cache management (new implementation is at end of function)
1199
1200
	r.POST("/api/pull", s.PullHandler)
	r.POST("/api/push", s.PushHandler)
1201
1202
	r.HEAD("/api/tags", s.ListHandler)
	r.GET("/api/tags", s.ListHandler)
1203
	r.POST("/api/show", s.ShowHandler)
1204
	r.DELETE("/api/delete", s.DeleteHandler)
1205
1206
1207

	// Create
	r.POST("/api/create", s.CreateHandler)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1208
1209
	r.POST("/api/blobs/:digest", s.CreateBlobHandler)
	r.HEAD("/api/blobs/:digest", s.HeadBlobHandler)
1210
1211
1212
	r.POST("/api/copy", s.CopyHandler)

	// Inference
1213
	r.GET("/api/ps", s.PsHandler)
1214
1215
1216
1217
	r.POST("/api/generate", s.GenerateHandler)
	r.POST("/api/chat", s.ChatHandler)
	r.POST("/api/embed", s.EmbedHandler)
	r.POST("/api/embeddings", s.EmbeddingsHandler)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1218

1219
	// Inference (OpenAI compatibility)
1220
	r.POST("/v1/chat/completions", openai.ChatMiddleware(), s.ChatHandler)
1221
	r.POST("/v1/completions", openai.CompletionsMiddleware(), s.GenerateHandler)
1222
	r.POST("/v1/embeddings", openai.EmbeddingsMiddleware(), s.EmbedHandler)
1223
1224
	r.GET("/v1/models", openai.ListMiddleware(), s.ListHandler)
	r.GET("/v1/models/:model", openai.RetrieveMiddleware(), s.ShowHandler)
1225

1226
1227
1228
1229
1230
1231
	if rc != nil {
		// wrap old with new
		rs := &registry.Local{
			Client:   rc,
			Logger:   slog.Default(), // TODO(bmizerany): Take a logger, do not use slog.Default()
			Fallback: r,
1232

1233
1234
1235
			Prune: PruneLayers,
		}
		return rs, nil
1236
1237
	}

1238
	return r, nil
1239
1240
1241
}

func Serve(ln net.Listener) error {
1242
	slog.SetDefault(logutil.NewLogger(os.Stderr, envconfig.LogLevel()))
1243
	slog.Info("server config", "env", envconfig.Values())
Michael Yang's avatar
Michael Yang committed
1244

1245
1246
1247
1248
1249
1250
1251
1252
	blobsDir, err := GetBlobsPath("")
	if err != nil {
		return err
	}
	if err := fixBlobs(blobsDir); err != nil {
		return err
	}

Michael Yang's avatar
bool  
Michael Yang committed
1253
	if !envconfig.NoPrune() {
1254
1255
1256
1257
1258
1259
1260
		if _, err := Manifests(false); err != nil {
			slog.Warn("corrupt manifests detected, skipping prune operation.  Re-pull or delete to clear", "error", err)
		} else {
			// clean up unused layers and manifests
			if err := PruneLayers(); err != nil {
				return err
			}
1261

1262
1263
1264
1265
			manifestsPath, err := GetManifestPath()
			if err != nil {
				return err
			}
1266

1267
1268
1269
			if err := PruneDirectory(manifestsPath); err != nil {
				return err
			}
1270
1271
1272
		}
	}

1273
1274
	s := &Server{addr: ln.Addr()}

1275
1276
1277
1278
1279
1280
1281
	var rc *ollama.Registry
	if useClient2 {
		var err error
		rc, err = ollama.DefaultRegistry()
		if err != nil {
			return err
		}
1282
1283
	}

1284
	h, err := s.GenerateRoutes(rc)
1285
1286
1287
	if err != nil {
		return err
	}
1288

1289
1290
	http.Handle("/", h)

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1291
	ctx, done := context.WithCancel(context.Background())
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1292
1293
	schedCtx, schedDone := context.WithCancel(ctx)
	sched := InitScheduler(schedCtx)
1294
	s.sched = sched
1295

1296
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1297
	srvr := &http.Server{
1298
1299
1300
1301
1302
1303
1304
1305
1306
		// Use http.DefaultServeMux so we get net/http/pprof for
		// free.
		//
		// TODO(bmizerany): Decide if we want to make this
		// configurable so it is not exposed by default, or allow
		// users to bind it to a different port. This was a quick
		// and easy way to get pprof, but it may not be the best
		// way.
		Handler: nil,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1307
1308
	}

1309
1310
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
1311
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
1312
1313
	go func() {
		<-signals
1314
		srvr.Close()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1315
		schedDone()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1316
		sched.unloadAllRunners()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1317
		done()
1318
1319
	}()

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1320
	s.sched.Run(schedCtx)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1321

1322
1323
1324
1325
	// register the experimental webp decoder
	// so webp images can be used in multimodal inputs
	image.RegisterFormat("webp", "RIFF????WEBP", webp.Decode, webp.DecodeConfig)

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1326
1327
	// 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
1328
	gpus := discover.GetGPUInfo()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1329
	gpus.LogDetails()
1330

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1331
1332
1333
1334
1335
1336
1337
	err = srvr.Serve(ln)
	// If server is closed from the signal handler, wait for the ctx to be done
	// otherwise error out quickly
	if !errors.Is(err, http.ErrServerClosed) {
		return err
	}
	<-ctx.Done()
1338
	return nil
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1339
}
Michael Yang's avatar
Michael Yang committed
1340

1341
func waitForStream(c *gin.Context, ch chan any) {
1342
	c.Header("Content-Type", "application/json")
1343
	var latest api.ProgressResponse
1344
1345
1346
	for resp := range ch {
		switch r := resp.(type) {
		case api.ProgressResponse:
1347
			latest = r
1348
		case gin.H:
Josh's avatar
Josh committed
1349
1350
1351
1352
			status, ok := r["status"].(int)
			if !ok {
				status = http.StatusInternalServerError
			}
1353
1354
1355
			errorMsg, ok := r["error"].(string)
			if !ok {
				errorMsg = "unknown error"
1356
			}
1357
1358
			c.JSON(status, gin.H{"error": errorMsg})
			return
1359
		default:
1360
			c.JSON(http.StatusInternalServerError, gin.H{"error": "unknown message type"})
1361
1362
1363
			return
		}
	}
1364
1365

	c.JSON(http.StatusOK, latest)
1366
1367
}

Michael Yang's avatar
Michael Yang committed
1368
func streamResponse(c *gin.Context, ch chan any) {
1369
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
1370
1371
1372
1373
1374
1375
1376
1377
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

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

1382
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
1383
1384
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
1385
			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1386
1387
1388
1389
1390
1391
			return false
		}

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

1393
func (s *Server) PsHandler(c *gin.Context) {
1394
	models := []api.ProcessModelResponse{}
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405

	for _, v := range s.sched.loaded {
		model := v.model
		modelDetails := api.ModelDetails{
			Format:            model.Config.ModelFormat,
			Family:            model.Config.ModelFamily,
			Families:          model.Config.ModelFamilies,
			ParameterSize:     model.Config.ModelType,
			QuantizationLevel: model.Config.FileType,
		}

1406
		mr := api.ProcessModelResponse{
1407
1408
1409
1410
1411
1412
1413
1414
			Model:     model.ShortName,
			Name:      model.ShortName,
			Size:      int64(v.estimatedTotal),
			SizeVRAM:  int64(v.estimatedVRAM),
			Digest:    model.Digest,
			Details:   modelDetails,
			ExpiresAt: v.expiresAt,
		}
1415
1416
1417
1418
1419
1420
1421
1422
		// The scheduler waits to set expiresAt, so if a model is loading it's
		// possible that it will be set to the unix epoch. For those cases, just
		// calculate the time w/ the sessionDuration instead.
		var epoch time.Time
		if v.expiresAt == epoch {
			mr.ExpiresAt = time.Now().Add(v.sessionDuration)
		}

1423
1424
1425
		models = append(models, mr)
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1426
1427
1428
1429
1430
	slices.SortStableFunc(models, func(i, j api.ProcessModelResponse) int {
		// longest duration remaining listed first
		return cmp.Compare(j.ExpiresAt.Unix(), i.ExpiresAt.Unix())
	})

1431
	c.JSON(http.StatusOK, api.ProcessResponse{Models: models})
1432
1433
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1434
func (s *Server) ChatHandler(c *gin.Context) {
1435
1436
	checkpointStart := time.Now()

Bruce MacDonald's avatar
Bruce MacDonald committed
1437
	var req api.ChatRequest
Michael Yang's avatar
Michael Yang committed
1438
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1439
1440
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
1441
	} else if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1442
1443
1444
1445
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Patrick Devine's avatar
Patrick Devine committed
1446
1447
1448
1449
1450
1451
1452
	// expire the runner
	if len(req.Messages) == 0 && req.KeepAlive != nil && int(req.KeepAlive.Seconds()) == 0 {
		model, err := GetModel(req.Model)
		if err != nil {
			switch {
			case os.IsNotExist(err):
				c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
1453
			case err.Error() == errtypes.InvalidModelNameErrMsg:
Patrick Devine's avatar
Patrick Devine committed
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
				c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			default:
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			}
			return
		}
		s.sched.expireRunner(model)

		c.JSON(http.StatusOK, api.ChatResponse{
			Model:      req.Model,
			CreatedAt:  time.Now().UTC(),
			Message:    api.Message{Role: "assistant"},
			Done:       true,
			DoneReason: "unload",
		})
		return
	}

1472
	caps := []model.Capability{model.CapabilityCompletion}
1473
	if len(req.Tools) > 0 {
1474
		caps = append(caps, model.CapabilityTools)
Michael Yang's avatar
tools  
Michael Yang committed
1475
	}
1476
1477
1478
	if req.Think != nil && *req.Think {
		caps = append(caps, model.CapabilityThinking)
	}
Michael Yang's avatar
tools  
Michael Yang committed
1479

1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
	name := model.ParseName(req.Model)
	if !name.IsValid() {
		c.JSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
	}
	name, err := getExistingName(name)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
	}

	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), caps, req.Options, req.KeepAlive)
Michael Yang's avatar
Michael Yang committed
1492
1493
	if errors.Is(err, errCapabilityCompletion) {
		c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("%q does not support chat", req.Model)})
Bruce MacDonald's avatar
Bruce MacDonald committed
1494
		return
Michael Yang's avatar
Michael Yang committed
1495
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
1496
		handleScheduleError(c, req.Model, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
1497
1498
		return
	}
Michael Yang's avatar
Michael Yang committed
1499

1500
1501
	checkpointLoaded := time.Now()

Michael Yang's avatar
Michael Yang committed
1502
1503
	if len(req.Messages) == 0 {
		c.JSON(http.StatusOK, api.ChatResponse{
1504
			Model:      req.Model,
Michael Yang's avatar
Michael Yang committed
1505
1506
			CreatedAt:  time.Now().UTC(),
			Message:    api.Message{Role: "assistant"},
1507
1508
			Done:       true,
			DoneReason: "load",
Michael Yang's avatar
Michael Yang committed
1509
		})
1510
1511
1512
		return
	}

Michael Yang's avatar
Michael Yang committed
1513
	msgs := append(m.Messages, req.Messages...)
1514
	if req.Messages[0].Role != "system" && m.System != "" {
Michael Yang's avatar
Michael Yang committed
1515
		msgs = append([]api.Message{{Role: "system", Content: m.System}}, msgs...)
1516
	}
1517
	msgs = filterThinkTags(msgs, m)
1518

1519
	prompt, images, err := chatPrompt(c.Request.Context(), m, r.Tokenize, opts, msgs, req.Tools, req.Think)
Michael Yang's avatar
Michael Yang committed
1520
	if err != nil {
1521
		slog.Error("chat prompt error", "error", err)
Michael Yang's avatar
Michael Yang committed
1522
1523
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
1524
1525
	}

1526
1527
	var thinkingState *thinking.Parser
	openingTag, closingTag := thinking.InferTags(m.Template.Template)
1528
	if req.Think != nil && *req.Think && openingTag != "" && closingTag != "" {
1529
		thinkingState = &thinking.Parser{
Devon Rifkin's avatar
Devon Rifkin committed
1530
1531
			OpeningTag: openingTag,
			ClosingTag: closingTag,
1532
1533
1534
		}
	}

1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
	var toolParser *tools.Parser
	if len(req.Tools) > 0 {
		toolParser, err = tools.NewParser(m.Template.Template)
		if err != nil {
			slog.Error("failed to create tool parser", "error", err)
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
1545
1546
1547
	ch := make(chan any)
	go func() {
		defer close(ch)
1548

Michael Yang's avatar
Michael Yang committed
1549
		if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
Michael Yang's avatar
Michael Yang committed
1550
1551
1552
			Prompt:  prompt,
			Images:  images,
			Format:  req.Format,
Michael Yang's avatar
Michael Yang committed
1553
			Options: opts,
Michael Yang's avatar
Michael Yang committed
1554
		}, func(r llm.CompletionResponse) {
1555
			res := api.ChatResponse{
1556
1557
1558
1559
				Model:     req.Model,
				CreatedAt: time.Now().UTC(),
				Message:   api.Message{Role: "assistant", Content: r.Content},
				Done:      r.Done,
Bruce MacDonald's avatar
Bruce MacDonald committed
1560
1561
1562
1563
1564
1565
1566
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}
1567

1568
			if thinkingState != nil {
Devon Rifkin's avatar
Devon Rifkin committed
1569
				thinkingContent, remainingContent := thinkingState.AddContent(res.Message.Content)
1570
1571
1572
1573
1574
1575
1576
1577
				if thinkingContent == "" && remainingContent == "" && !r.Done {
					// need to accumulate more to decide what to send
					return
				}
				res.Message.Content = remainingContent
				res.Message.Thinking = thinkingContent
			}

1578
			if r.Done {
1579
				res.DoneReason = r.DoneReason.String()
1580
1581
1582
1583
				res.TotalDuration = time.Since(checkpointStart)
				res.LoadDuration = checkpointLoaded.Sub(checkpointStart)
			}

1584
			if len(req.Tools) > 0 {
1585
				toolCalls, content := toolParser.Add(res.Message.Content)
1586
1587
1588
1589
1590
				if len(content) > 0 {
					res.Message.Content = content
				} else if len(toolCalls) > 0 {
					res.Message.ToolCalls = toolCalls
					res.Message.Content = ""
1591
1592
				} else if res.Message.Thinking != "" {
					// don't return
1593
1594
1595
1596
1597
				} else {
					if r.Done {
						ch <- res
					}
					return
1598
1599
				}
			}
1600

1601
			ch <- res
Michael Yang's avatar
Michael Yang committed
1602
		}); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1603
1604
1605
1606
1607
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
Michael Yang's avatar
tools  
Michael Yang committed
1608
		var resp api.ChatResponse
1609
		var toolCalls []api.ToolCall
1610
1611
		var sbThinking strings.Builder
		var sbContent strings.Builder
Michael Yang's avatar
Michael Yang committed
1612
1613
		for rr := range ch {
			switch t := rr.(type) {
1614
			case api.ChatResponse:
1615
1616
				sbThinking.WriteString(t.Message.Thinking)
				sbContent.WriteString(t.Message.Content)
Michael Yang's avatar
tools  
Michael Yang committed
1617
				resp = t
1618
1619
1620
				if len(req.Tools) > 0 {
					toolCalls = append(toolCalls, t.Message.ToolCalls...)
				}
1621
			case gin.H:
Michael Yang's avatar
Michael Yang committed
1622
1623
1624
				msg, ok := t["error"].(string)
				if !ok {
					msg = "unexpected error format in response"
1625
				}
Michael Yang's avatar
Michael Yang committed
1626
1627
1628

				c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
				return
1629
			default:
Michael Yang's avatar
Michael Yang committed
1630
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
1631
				return
Bruce MacDonald's avatar
Bruce MacDonald committed
1632
1633
			}
		}
1634

1635
1636
1637
		resp.Message.Content = sbContent.String()
		resp.Message.Thinking = sbThinking.String()

1638
1639
		if len(toolCalls) > 0 {
			resp.Message.ToolCalls = toolCalls
Michael Yang's avatar
tools  
Michael Yang committed
1640
1641
1642
		}

		c.JSON(http.StatusOK, resp)
Bruce MacDonald's avatar
Bruce MacDonald committed
1643
1644
1645
1646
1647
		return
	}

	streamResponse(c, ch)
}
1648

Michael Yang's avatar
Michael Yang committed
1649
func handleScheduleError(c *gin.Context, name string, err error) {
Michael Yang's avatar
Michael Yang committed
1650
	switch {
1651
	case errors.Is(err, errCapabilities), errors.Is(err, errRequired):
Michael Yang's avatar
Michael Yang committed
1652
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
1653
	case errors.Is(err, context.Canceled):
1654
		c.JSON(499, gin.H{"error": "request canceled"})
Michael Yang's avatar
Michael Yang committed
1655
	case errors.Is(err, ErrMaxQueue):
1656
		c.JSON(http.StatusServiceUnavailable, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
1657
1658
	case errors.Is(err, os.ErrNotExist):
		c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model %q not found, try pulling it first", name)})
Michael Yang's avatar
Michael Yang committed
1659
1660
	default:
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
1661
1662
	}
}
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674

func filterThinkTags(msgs []api.Message, m *Model) []api.Message {
	if m.Config.ModelFamily == "qwen3" || model.ParseName(m.Name).Model == "deepseek-r1" {
		finalUserIndex := -1
		for i, msg := range msgs {
			if msg.Role == "user" {
				finalUserIndex = i
			}
		}

		for i, msg := range msgs {
			if msg.Role == "assistant" && i < finalUserIndex {
1675
1676
1677
1678
1679
				// TODO(drifkin): this is from before we added proper thinking support.
				// However, even if thinking is not enabled (and therefore we shouldn't
				// change the user output), we should probably perform this filtering
				// for all thinking models (not just qwen3 & deepseek-r1) since it tends
				// to save tokens and improve quality.
1680
				thinkingState := &thinking.Parser{
Devon Rifkin's avatar
Devon Rifkin committed
1681
1682
					OpeningTag: "<think>",
					ClosingTag: "</think>",
1683
				}
Devon Rifkin's avatar
Devon Rifkin committed
1684
				_, content := thinkingState.AddContent(msg.Content)
1685
				msgs[i].Content = content
1686
1687
1688
1689
1690
			}
		}
	}
	return msgs
}