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

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

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

32
	"github.com/ollama/ollama/api"
33
	"github.com/ollama/ollama/auth"
34
	"github.com/ollama/ollama/discover"
35
	"github.com/ollama/ollama/envconfig"
36
	"github.com/ollama/ollama/format"
Michael Yang's avatar
Michael Yang committed
37
	"github.com/ollama/ollama/fs/ggml"
38
	"github.com/ollama/ollama/llm"
39
	"github.com/ollama/ollama/logutil"
40
	"github.com/ollama/ollama/middleware"
Devon Rifkin's avatar
Devon Rifkin committed
41
	"github.com/ollama/ollama/model/parsers"
42
43
	"github.com/ollama/ollama/server/internal/client/ollama"
	"github.com/ollama/ollama/server/internal/registry"
Michael Yang's avatar
Michael Yang committed
44
	"github.com/ollama/ollama/template"
45
	"github.com/ollama/ollama/thinking"
46
	"github.com/ollama/ollama/tools"
47
	"github.com/ollama/ollama/types/errtypes"
Michael Yang's avatar
Michael Yang committed
48
	"github.com/ollama/ollama/types/model"
49
	"github.com/ollama/ollama/version"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
50
51
)

52
53
const signinURLStr = "https://ollama.com/connect?name=%s&key=%s"

54
55
56
57
58
59
60
61
62
63
64
65
func shouldUseHarmony(model *Model) bool {
	if slices.Contains([]string{"gptoss", "gpt-oss"}, model.Config.ModelFamily) {
		// heuristic to check whether the template expects to be parsed via harmony:
		// search for harmony tags that are nearly always used
		if model.Template.Contains("<|start|>") && model.Template.Contains("<|end|>") {
			return true
		}
	}

	return false
}

66
67
68
69
70
71
func experimentEnabled(name string) bool {
	return slices.Contains(strings.Split(os.Getenv("OLLAMA_EXPERIMENT"), ","), name)
}

var useClient2 = experimentEnabled("client2")

72
73
74
75
// Low VRAM mode is based on the sum of total VRAM (not free) and triggers
// reduced context length on some models
var lowVRAMThreshold uint64 = 20 * format.GibiByte

Michael Yang's avatar
Michael Yang committed
76
77
var mode string = gin.DebugMode

78
type Server struct {
79
80
81
	addr    net.Addr
	sched   *Scheduler
	lowVRAM bool
82
83
}

Michael Yang's avatar
Michael Yang committed
84
85
86
87
88
89
90
91
92
93
94
95
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
96
97
98
99
var (
	errRequired    = errors.New("is required")
	errBadTemplate = errors.New("template error")
)
Michael Yang's avatar
Michael Yang committed
100

101
func modelOptions(model *Model, requestOpts map[string]any) (api.Options, error) {
102
103
104
105
106
107
108
109
110
111
	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
112
113
}

Michael Yang's avatar
Michael Yang committed
114
115
// 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.
116
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
117
	if name == "" {
Michael Yang's avatar
Michael Yang committed
118
		return nil, nil, nil, fmt.Errorf("model %w", errRequired)
Bruce MacDonald's avatar
Bruce MacDonald committed
119
120
	}

Michael Yang's avatar
Michael Yang committed
121
	model, err := GetModel(name)
Bruce MacDonald's avatar
Bruce MacDonald committed
122
	if err != nil {
Michael Yang's avatar
Michael Yang committed
123
		return nil, nil, nil, err
124
125
	}

126
127
128
129
	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
130
	if err := model.CheckCapabilities(caps...); err != nil {
Michael Yang's avatar
Michael Yang committed
131
		return nil, nil, nil, fmt.Errorf("%s %w", name, err)
132
133
	}

Michael Yang's avatar
Michael Yang committed
134
	opts, err := modelOptions(model, requestOpts)
135
	if err != nil {
Michael Yang's avatar
Michael Yang committed
136
		return nil, nil, nil, err
137
138
	}

139
140
	// This model is much more capable with a larger context, so set that
	// unless it would penalize performance too much
141
	if !s.lowVRAM && slices.Contains([]string{"gptoss", "gpt-oss"}, model.Config.ModelFamily) {
Michael Yang's avatar
Michael Yang committed
142
143
144
		opts.NumCtx = max(opts.NumCtx, 8192)
	}

Michael Yang's avatar
Michael Yang committed
145
	runnerCh, errCh := s.sched.GetRunner(ctx, model, opts, keepAlive)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
146
147
	var runner *runnerRef
	select {
Michael Yang's avatar
Michael Yang committed
148
149
	case runner = <-runnerCh:
	case err = <-errCh:
Michael Yang's avatar
Michael Yang committed
150
		return nil, nil, nil, err
Bruce MacDonald's avatar
Bruce MacDonald committed
151
152
	}

Michael Yang's avatar
Michael Yang committed
153
	return runner.llama, model, &opts, nil
Michael Yang's avatar
Michael Yang committed
154
155
}

156
157
158
159
160
161
162
163
164
165
166
func signinURL() (string, error) {
	pubKey, err := auth.GetPublicKey()
	if err != nil {
		return "", err
	}

	encKey := base64.RawURLEncoding.EncodeToString([]byte(pubKey))
	h, _ := os.Hostname()
	return fmt.Sprintf(signinURLStr, url.PathEscape(h), encKey), nil
}

Michael Yang's avatar
Michael Yang committed
167
func (s *Server) GenerateHandler(c *gin.Context) {
168
	checkpointStart := time.Now()
Michael Yang's avatar
Michael Yang committed
169
170
171
172
173
174
	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
175
176
177
		return
	}

178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
	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
	}

194
	m, err := GetModel(name.String())
195
196
	if err != nil {
		switch {
197
		case errors.Is(err, fs.ErrNotExist):
198
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
199
		case err.Error() == errtypes.InvalidModelNameErrMsg:
200
201
202
203
204
205
206
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
	if m.Config.RemoteHost != "" && m.Config.RemoteModel != "" {
		origModel := req.Model

		remoteURL, err := url.Parse(m.Config.RemoteHost)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		if !slices.Contains(envconfig.Remotes(), remoteURL.Hostname()) {
			slog.Info("remote model", "remotes", envconfig.Remotes(), "remoteURL", m.Config.RemoteHost, "hostname", remoteURL.Hostname())
			c.JSON(http.StatusBadRequest, gin.H{"error": "this server cannot run this remote model"})
			return
		}

		req.Model = m.Config.RemoteModel

		if req.Template == "" && m.Template.String() != "" {
			req.Template = m.Template.String()
		}

		if req.Options == nil {
			req.Options = map[string]any{}
		}

		for k, v := range m.Options {
			if _, ok := req.Options[k]; !ok {
				req.Options[k] = v
			}
		}

		// update the system prompt from the model if one isn't already specified
		if req.System == "" && m.System != "" {
			req.System = m.System
		}

		if len(m.Messages) > 0 {
			slog.Warn("embedded messages in the model not supported with '/api/generate'; try '/api/chat' instead")
		}

		fn := func(resp api.GenerateResponse) error {
			resp.Model = origModel
			resp.RemoteModel = m.Config.RemoteModel
			resp.RemoteHost = m.Config.RemoteHost

			data, err := json.Marshal(resp)
			if err != nil {
				return err
			}

			if _, err = c.Writer.Write(append(data, '\n')); err != nil {
				return err
			}
			c.Writer.Flush()
			return nil
		}

		client := api.NewClient(remoteURL, http.DefaultClient)
		err = client.Generate(c, &req, fn)
		if err != nil {
267
268
269
270
271
272
			var authError api.AuthorizationError
			if errors.As(err, &authError) {
				sURL, sErr := signinURL()
				if sErr != nil {
					slog.Error(sErr.Error())
					c.JSON(http.StatusInternalServerError, gin.H{"error": "error getting authorization details"})
273
274
					return
				}
275
276
277
278
279
280
281

				c.JSON(authError.StatusCode, gin.H{"error": "unauthorized", "signin_url": sURL})
				return
			}
			var apiError api.StatusError
			if errors.As(err, &apiError) {
				c.JSON(apiError.StatusCode, apiError)
282
283
284
285
286
287
288
289
290
				return
			}
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		return
	}

Patrick Devine's avatar
Patrick Devine committed
291
	// expire the runner
Michael Yang's avatar
Michael Yang committed
292
	if req.Prompt == "" && req.KeepAlive != nil && req.KeepAlive.Duration == 0 {
293
		s.sched.expireRunner(m)
Patrick Devine's avatar
Patrick Devine committed
294
295
296
297
298
299
300
301
302
303
304

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

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

310
311
312
313
314
315
316
317
318
319
320
	var builtinParser parsers.Parser
	if shouldUseHarmony(m) && m.Config.Parser == "" {
		m.Config.Parser = "harmony"
	}

	if !req.Raw && m.Config.Parser != "" {
		builtinParser = parsers.ParserForName(m.Config.Parser)
		if builtinParser != nil {
			// no tools or last message for generate endpoint
			builtinParser.Init(nil, nil)
		}
Michael Yang's avatar
Michael Yang committed
321
322
	}

323
324
	// Validate Think value: string values currently only allowed for harmony/gptoss models
	if req.Think != nil && req.Think.IsString() && m.Config.Parser != "harmony" {
325
		c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("think value %q is not supported for this model", req.Think.String())})
Michael Yang's avatar
Michael Yang committed
326
327
328
		return
	}

329
	caps := []model.Capability{model.CapabilityCompletion}
330
	if req.Suffix != "" {
331
		caps = append(caps, model.CapabilityInsert)
332
	}
333
334

	modelCaps := m.Capabilities()
335
	if slices.Contains(modelCaps, model.CapabilityThinking) {
336
		caps = append(caps, model.CapabilityThinking)
337
		if req.Think == nil {
338
339
			req.Think = &api.ThinkValue{Value: true}
		}
340
341
342
343
344
	} else {
		if req.Think != nil && req.Think.Bool() {
			c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("%q does not support thinking", req.Model)})
			return
		}
345
	}
346

347
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), caps, req.Options, req.KeepAlive)
Michael Yang's avatar
Michael Yang committed
348
349
350
351
	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
352
353
354
355
		handleScheduleError(c, req.Model, err)
		return
	}

356
357
	checkpointLoaded := time.Now()

358
	// load the model
Michael Yang's avatar
Michael Yang committed
359
360
361
362
363
364
365
	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
366
367
		return
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
368

369
370
	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"})
371
372
373
		return
	}

Michael Yang's avatar
Michael Yang committed
374
375
	images := make([]llm.ImageData, len(req.Images))
	for i := range req.Images {
376
		images[i] = llm.ImageData{ID: i, Data: req.Images[i]}
Michael Yang's avatar
Michael Yang committed
377
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
378

Michael Yang's avatar
Michael Yang committed
379
380
	prompt := req.Prompt
	if !req.Raw {
Michael Yang's avatar
Michael Yang committed
381
		tmpl := m.Template
Michael Yang's avatar
Michael Yang committed
382
383
384
385
386
387
388
389
		if req.Template != "" {
			tmpl, err = template.Parse(req.Template)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}

390
391
392
393
394
395
396
397
398
399
400
401
		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
402
403
404
405
			if req.Context == nil {
				msgs = append(msgs, m.Messages...)
			}

406
			userMsg := api.Message{Role: "user", Content: req.Prompt}
407
			for _, i := range images {
408
				userMsg.Images = append(userMsg.Images, i.Data)
409
			}
410
			values.Messages = append(msgs, userMsg)
411
412
		}

413
		values.Think = req.Think != nil && req.Think.Bool()
Michael Yang's avatar
Michael Yang committed
414
415
		values.ThinkLevel = ""
		if req.Think != nil {
416
			values.ThinkLevel = req.Think.String()
Michael Yang's avatar
Michael Yang committed
417
		}
418
419
		values.IsThinkSet = req.Think != nil

Michael Yang's avatar
Michael Yang committed
420
421
		var b bytes.Buffer
		if req.Context != nil {
422
			slog.Warn("the context field is deprecated and will be removed in a future version of Ollama")
423
			s, err := r.Detokenize(c.Request.Context(), req.Context)
Michael Yang's avatar
Michael Yang committed
424
425
426
427
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
428
			b.WriteString(s)
Michael Yang's avatar
Michael Yang committed
429
		}
430

431
432
433
434
435
436
		// check that we're in the `api/chat`-like flow, and if so, generate the
		// prompt the same way
		// TEMP(drifkin): we should really just detect the chat-like flow and call
		// the real chat handler, but doing this as a stopgap to get renderer
		// support for generate
		if values.Messages != nil && values.Suffix == "" && req.Template == "" {
437
			prompt, images, err = chatPrompt(c.Request.Context(), m, r.Tokenize, opts, values.Messages, []api.Tool{}, req.Think, req.Truncate == nil || *req.Truncate)
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
			// TEMP(drifkin): req.Context will be removed very soon, but we're temporarily supporting it in this flow here
			if req.Context != nil {
				b.WriteString(prompt)
				prompt = b.String()
			}
		} else {
			// legacy flow
			if err := tmpl.Execute(&b, values); err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
453

454
455
			prompt = b.String()
		}
Bruce MacDonald's avatar
Bruce MacDonald committed
456
457
	}

458
459
	// If debug mode is enabled, return the rendered template instead of calling the model
	if req.DebugRenderOnly {
Devon Rifkin's avatar
Devon Rifkin committed
460
		c.JSON(http.StatusOK, api.GenerateResponse{
461
462
			Model:     req.Model,
			CreatedAt: time.Now().UTC(),
Devon Rifkin's avatar
Devon Rifkin committed
463
			DebugInfo: &api.DebugInfo{
464
465
466
467
468
469
470
				RenderedTemplate: prompt,
				ImageCount:       len(images),
			},
		})
		return
	}

471
	var thinkingState *thinking.Parser
472
	if builtinParser == nil {
Michael Yang's avatar
Michael Yang committed
473
		openingTag, closingTag := thinking.InferTags(m.Template.Template)
474
		if req.Think != nil && req.Think.Bool() && openingTag != "" && closingTag != "" {
Michael Yang's avatar
Michael Yang committed
475
476
477
478
			thinkingState = &thinking.Parser{
				OpeningTag: openingTag,
				ClosingTag: closingTag,
			}
479
480
481
			if strings.HasSuffix(strings.TrimSpace(prompt), openingTag) {
				thinkingState.AddContent(openingTag)
			}
482
483
484
		}
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
485
486
	ch := make(chan any)
	go func() {
487
488
		// TODO (jmorganca): avoid building the response twice both here and below
		var sb strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
489
		defer close(ch)
Michael Yang's avatar
Michael Yang committed
490
		if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
491
492
493
494
495
496
			Prompt:   prompt,
			Images:   images,
			Format:   req.Format,
			Options:  opts,
			Shift:    req.Shift == nil || *req.Shift,
			Truncate: req.Truncate == nil || *req.Truncate,
497
498
		}, func(cr llm.CompletionResponse) {
			res := api.GenerateResponse{
499
500
501
502
				Model:     req.Model,
				CreatedAt: time.Now().UTC(),
				Response:  cr.Content,
				Done:      cr.Done,
Bruce MacDonald's avatar
Bruce MacDonald committed
503
				Metrics: api.Metrics{
504
505
506
507
					PromptEvalCount:    cr.PromptEvalCount,
					PromptEvalDuration: cr.PromptEvalDuration,
					EvalCount:          cr.EvalCount,
					EvalDuration:       cr.EvalDuration,
Bruce MacDonald's avatar
Bruce MacDonald committed
508
				},
Bruce MacDonald's avatar
Bruce MacDonald committed
509
			}
510

511
512
513
514
515
516
			if builtinParser != nil {
				content, thinking, toolCalls, err := builtinParser.Add(cr.Content, cr.Done)
				if err != nil {
					ch <- gin.H{"error": err.Error()}
					return
				}
517
518
				res.Response = content
				res.Thinking = thinking
519
520
521
				if cr.Done && len(toolCalls) > 0 {
					res.ToolCalls = toolCalls
				}
522
			} else if thinkingState != nil {
Devon Rifkin's avatar
Devon Rifkin committed
523
				thinking, content := thinkingState.AddContent(cr.Content)
524
525
526
527
				res.Thinking = thinking
				res.Response = content
			}

528
529
530
531
532
			if _, err := sb.WriteString(cr.Content); err != nil {
				ch <- gin.H{"error": err.Error()}
			}

			if cr.Done {
533
534
535
536
				res.DoneReason = cr.DoneReason.String()
				res.TotalDuration = time.Since(checkpointStart)
				res.LoadDuration = checkpointLoaded.Sub(checkpointStart)

537
				if !req.Raw {
538
					tokens, err := r.Tokenize(c.Request.Context(), prompt+sb.String())
539
540
541
542
					if err != nil {
						ch <- gin.H{"error": err.Error()}
						return
					}
543
					res.Context = tokens
544
545
546
				}
			}

547
			if builtinParser != nil {
Michael Yang's avatar
Michael Yang committed
548
549
550
551
552
553
554
555
				// only send messages with meaningful content (empty messages confuse clients)
				if res.Response != "" || res.Thinking != "" || res.Done || len(res.ToolCalls) > 0 {
					ch <- res
				}

				return
			}

556
			ch <- res
Michael Yang's avatar
Michael Yang committed
557
		}); err != nil {
558
559
560
561
562
563
			var serr api.StatusError
			if errors.As(err, &serr) {
				ch <- gin.H{"error": serr.ErrorMessage, "status": serr.StatusCode}
			} else {
				ch <- gin.H{"error": err.Error()}
			}
Bruce MacDonald's avatar
Bruce MacDonald committed
564
565
566
567
		}
	}()

	if req.Stream != nil && !*req.Stream {
Michael Yang's avatar
Michael Yang committed
568
		var r api.GenerateResponse
569
570
		var sbThinking strings.Builder
		var sbContent strings.Builder
Michael Yang's avatar
Michael Yang committed
571
572
		for rr := range ch {
			switch t := rr.(type) {
573
			case api.GenerateResponse:
574
575
				sbThinking.WriteString(t.Thinking)
				sbContent.WriteString(t.Response)
Michael Yang's avatar
Michael Yang committed
576
				r = t
577
578
579
580
581
582
			case gin.H:
				msg, ok := t["error"].(string)
				if !ok {
					msg = "unexpected error format in response"
				}

583
584
585
586
587
588
				status, ok := t["status"].(int)
				if !ok {
					status = http.StatusInternalServerError
				}

				c.JSON(status, gin.H{"error": msg})
Michael Yang's avatar
Michael Yang committed
589
				return
590
			default:
Michael Yang's avatar
Michael Yang committed
591
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
Bruce MacDonald's avatar
Bruce MacDonald committed
592
593
594
				return
			}
		}
595

596
597
598
		r.Thinking = sbThinking.String()
		r.Response = sbContent.String()

Michael Yang's avatar
Michael Yang committed
599
		c.JSON(http.StatusOK, r)
Bruce MacDonald's avatar
Bruce MacDonald committed
600
601
602
603
604
605
		return
	}

	streamResponse(c, ch)
}

606
func (s *Server) EmbedHandler(c *gin.Context) {
607
	checkpointStart := time.Now()
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
	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:
640
641
642
643
		if req.Input != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid input type"})
			return
		}
644
645
	}

646
647
648
649
650
651
	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
	}

652
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), []model.Capability{}, req.Options, req.KeepAlive)
653
654
655
656
657
	if err != nil {
		handleScheduleError(c, req.Model, err)
		return
	}

658
659
	checkpointLoaded := time.Now()

660
661
662
663
664
	if len(input) == 0 {
		c.JSON(http.StatusOK, api.EmbedResponse{Model: req.Model, Embeddings: [][]float32{}})
		return
	}

665
	kvData, _, err := getModelData(m.ModelPath, false)
666
667
668
669
670
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

671
	var count int
672
673
674
675
676
677
678
679
680
681
	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 {
682
				c.JSON(http.StatusBadRequest, gin.H{"error": "input exceeds maximum context length"})
683
684
685
				return
			}

686
687
688
689
690
691
692
693
			if bos := kvData.Uint("tokenizer.ggml.bos_token_id"); tokens[0] != int(bos) && kvData.Bool("add_bos_token", true) {
				ctxLen--
			}

			if eos := kvData.Uint("tokenizer.ggml.eos_token_id"); tokens[len(tokens)-1] != int(eos) && kvData.Bool("add_eos_token", true) {
				ctxLen--
			}

694
695
696
697
698
699
700
			slog.Info("", "ctxLen", ctxLen, "tokenCount", len(tokens))
			if ctxLen <= 0 {
				// return error if the truncated input would be empty or just special tokens
				c.JSON(http.StatusBadRequest, gin.H{"error": "input after truncation exceeds maximum context length"})
				return
			}

701
			tokens = tokens[:ctxLen]
702

703
704
705
706
707
708
709
			s, err = r.Detokenize(c.Request.Context(), tokens)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}

710
711
		count += len(tokens)

712
713
		input[i] = s
	}
714
715
716
717
718
719
720
721
722

	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
			}
723
724
725
726
727
728
			// TODO: this first normalization should be done by the model
			embedding = normalize(embedding)
			if req.Dimensions > 0 && req.Dimensions < len(embedding) {
				embedding = normalize(embedding[:req.Dimensions])
			}
			embeddings[i] = embedding
729
730
			return nil
		})
731
732
	}

733
	if err := g.Wait(); err != nil {
734
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": strings.TrimSpace(err.Error())})
735
		return
736
737
738
	}

	resp := api.EmbedResponse{
739
		Model:           req.Model,
740
		Embeddings:      embeddings,
741
742
		TotalDuration:   time.Since(checkpointStart),
		LoadDuration:    checkpointLoaded.Sub(checkpointStart),
743
		PromptEvalCount: count,
744
745
746
747
748
749
750
751
752
753
	}
	c.JSON(http.StatusOK, resp)
}

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

754
	norm := float32(1.0 / max(math.Sqrt(float64(sum)), 1e-12))
755
756
757
758
759
760
	for i := range vec {
		vec[i] *= norm
	}
	return vec
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
761
func (s *Server) EmbeddingsHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
762
	var req api.EmbeddingRequest
Michael Yang's avatar
Michael Yang committed
763
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
Bruce MacDonald's avatar
Bruce MacDonald committed
764
765
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
766
	} else if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
767
768
769
770
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

771
772
773
774
775
776
	name := model.ParseName(req.Model)
	if !name.IsValid() {
		c.JSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
	}

777
	r, _, _, err := s.scheduleRunner(c.Request.Context(), name.String(), []model.Capability{}, req.Options, req.KeepAlive)
Bruce MacDonald's avatar
Bruce MacDonald committed
778
	if err != nil {
Michael Yang's avatar
Michael Yang committed
779
		handleScheduleError(c, req.Model, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
780
781
782
		return
	}

783
784
785
	// an empty request loads the model
	if req.Prompt == "" {
		c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: []float64{}})
Bruce MacDonald's avatar
Bruce MacDonald committed
786
787
788
		return
	}

789
	embedding, err := r.Embedding(c.Request.Context(), req.Prompt)
Bruce MacDonald's avatar
Bruce MacDonald committed
790
	if err != nil {
791
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": strings.TrimSpace(err.Error())})
Bruce MacDonald's avatar
Bruce MacDonald committed
792
793
794
		return
	}

795
796
797
	var e []float64
	for _, v := range embedding {
		e = append(e, float64(v))
798
799
800
	}

	resp := api.EmbeddingResponse{
801
		Embedding: e,
802
803
	}
	c.JSON(http.StatusOK, resp)
Bruce MacDonald's avatar
Bruce MacDonald committed
804
805
}

806
func (s *Server) PullHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
807
	var req api.PullRequest
Michael Yang's avatar
Michael Yang committed
808
809
810
811
812
813
814
	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
815
816
817
		return
	}

818
819
	name := model.ParseName(cmp.Or(req.Model, req.Name))
	if !name.IsValid() {
820
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": errtypes.InvalidModelNameErrMsg})
821
822
823
		return
	}

824
825
	name, err = getExistingName(name)
	if err != nil {
826
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
827
828
829
		return
	}

830
831
832
	ch := make(chan any)
	go func() {
		defer close(ch)
833
834
		fn := func(r api.ProgressResponse) {
			ch <- r
835
		}
836

Michael Yang's avatar
Michael Yang committed
837
		regOpts := &registryOptions{
838
839
840
			Insecure: req.Insecure,
		}

841
842
843
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

844
		if err := PullModel(ctx, name.DisplayShortest(), regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
845
			ch <- gin.H{"error": err.Error()}
846
847
848
		}
	}()

849
850
851
852
853
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

854
855
856
	streamResponse(c, ch)
}

857
func (s *Server) PushHandler(c *gin.Context) {
858
	var req api.PushRequest
Michael Yang's avatar
Michael Yang committed
859
860
861
862
863
864
865
	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
866
867
		return
	}
Michael Yang's avatar
Michael Yang committed
868

869
	var mname string
Michael Yang's avatar
Michael Yang committed
870
	if req.Model != "" {
871
		mname = req.Model
Michael Yang's avatar
Michael Yang committed
872
	} else if req.Name != "" {
873
		mname = req.Name
Michael Yang's avatar
Michael Yang committed
874
875
	} else {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
876
877
878
		return
	}

879
880
881
	ch := make(chan any)
	go func() {
		defer close(ch)
882
883
		fn := func(r api.ProgressResponse) {
			ch <- r
884
		}
885

Michael Yang's avatar
Michael Yang committed
886
		regOpts := &registryOptions{
887
888
889
			Insecure: req.Insecure,
		}

Michael Yang's avatar
Michael Yang committed
890
891
892
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

893
894
895
896
897
898
899
		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
900
			ch <- gin.H{"error": err.Error()}
901
902
903
		}
	}()

904
905
906
907
908
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

909
910
911
	streamResponse(c, ch)
}

912
913
914
915
// 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.
916
917
918
func getExistingName(n model.Name) (model.Name, error) {
	var zero model.Name
	existing, err := Manifests(true)
919
	if err != nil {
920
		return zero, err
921
	}
922
	var set model.Name // tracks parts already canonicalized
923
	for e := range existing {
924
925
926
927
928
929
930
931
932
933
934
		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
935
936
		}
	}
937
	return n, nil
938
939
}

940
func (s *Server) DeleteHandler(c *gin.Context) {
941
942
	var r api.DeleteRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
943
944
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
945
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
946
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
947
948
949
		return
	}

950
951
952
	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))})
953
954
		return
	}
Michael Yang's avatar
Michael Yang committed
955

956
957
958
959
960
961
	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
	}

962
	m, err := ParseNamedManifest(n)
Michael Yang's avatar
Michael Yang committed
963
	if err != nil {
964
965
966
967
968
969
		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
970
971
972
		return
	}

973
	if err := m.Remove(); err != nil {
Michael Yang's avatar
Michael Yang committed
974
975
976
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
977
978
979
980
981

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

984
func (s *Server) ShowHandler(c *gin.Context) {
Patrick Devine's avatar
Patrick Devine committed
985
	var req api.ShowRequest
Michael Yang's avatar
Michael Yang committed
986
987
988
989
990
991
992
	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
993
994
995
		return
	}

Michael Yang's avatar
Michael Yang committed
996
	if req.Model != "" {
Michael Yang's avatar
Michael Yang committed
997
		// noop
Michael Yang's avatar
Michael Yang committed
998
	} else if req.Name != "" {
Michael Yang's avatar
Michael Yang committed
999
		req.Model = req.Name
Michael Yang's avatar
Michael Yang committed
1000
	} else {
1001
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
1002
1003
1004
		return
	}

1005
	resp, err := GetModelInfo(req)
Patrick Devine's avatar
Patrick Devine committed
1006
	if err != nil {
1007
1008
		switch {
		case os.IsNotExist(err):
Michael Yang's avatar
Michael Yang committed
1009
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
1010
		case err.Error() == errtypes.InvalidModelNameErrMsg:
1011
1012
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
Patrick Devine's avatar
Patrick Devine committed
1013
1014
1015
1016
1017
1018
1019
1020
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

	c.JSON(http.StatusOK, resp)
}

1021
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
1022
1023
	name := model.ParseName(req.Model)
	if !name.IsValid() {
CYJiang's avatar
CYJiang committed
1024
		return nil, ErrModelPathInvalid
1025
1026
1027
1028
1029
1030
1031
	}
	name, err := getExistingName(name)
	if err != nil {
		return nil, err
	}

	m, err := GetModel(name.String())
Patrick Devine's avatar
Patrick Devine committed
1032
1033
1034
1035
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
1036
	modelDetails := api.ModelDetails{
1037
1038
1039
1040
1041
1042
		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
1043
1044
	}

1045
	if req.System != "" {
1046
		m.System = req.System
1047
1048
	}

Michael Yang's avatar
Michael Yang committed
1049
1050
1051
	msgs := make([]api.Message, len(m.Messages))
	for i, msg := range m.Messages {
		msgs[i] = api.Message{Role: msg.Role, Content: msg.Content}
1052
1053
	}

1054
	manifest, err := ParseNamedManifest(name)
1055
1056
1057
1058
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
1059
	resp := &api.ShowResponse{
1060
1061
1062
1063
1064
1065
1066
		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
1067
1068
	}

1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
	if m.Config.RemoteHost != "" {
		resp.RemoteHost = m.Config.RemoteHost
		resp.RemoteModel = m.Config.RemoteModel

		if m.Config.ModelFamily != "" {
			resp.ModelInfo = make(map[string]any)
			resp.ModelInfo["general.architecture"] = m.Config.ModelFamily

			if m.Config.BaseName != "" {
				resp.ModelInfo["general.basename"] = m.Config.BaseName
			}

			if m.Config.ContextLen > 0 {
				resp.ModelInfo[fmt.Sprintf("%s.context_length", m.Config.ModelFamily)] = m.Config.ContextLen
			}

			if m.Config.EmbedLen > 0 {
				resp.ModelInfo[fmt.Sprintf("%s.embedding_length", m.Config.ModelFamily)] = m.Config.EmbedLen
			}
		}
	}

Patrick Devine's avatar
Patrick Devine committed
1091
1092
	var params []string
	cs := 30
1093
	for k, v := range m.Options {
Patrick Devine's avatar
Patrick Devine committed
1094
		switch val := v.(type) {
1095
		case []any:
Patrick Devine's avatar
Patrick Devine committed
1096
			for _, nv := range val {
Patrick Devine's avatar
Patrick Devine committed
1097
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
Patrick Devine's avatar
Patrick Devine committed
1098
			}
Patrick Devine's avatar
Patrick Devine committed
1099
1100
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
Patrick Devine's avatar
Patrick Devine committed
1101
1102
1103
1104
		}
	}
	resp.Parameters = strings.Join(params, "\n")

Patrick Devine's avatar
Patrick Devine committed
1105
1106
1107
1108
1109
	if len(req.Options) > 0 {
		if m.Options == nil {
			m.Options = make(map[string]any)
		}
		for k, v := range req.Options {
1110
			m.Options[k] = v
1111
1112
1113
		}
	}

1114
	var sb strings.Builder
1115
	fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"")
1116
	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
1117
1118
	fmt.Fprintf(&sb, "# FROM %s\n\n", m.ShortName)
	fmt.Fprint(&sb, m.String())
1119
	resp.Modelfile = sb.String()
1120

1121
1122
1123
1124
1125
	// skip loading tensor information if this is a remote model
	if m.Config.RemoteHost != "" && m.Config.RemoteModel != "" {
		return resp, nil
	}

1126
	kvData, tensors, err := getModelData(m.ModelPath, req.Verbose)
1127
1128
1129
	if err != nil {
		return nil, err
	}
1130

1131
1132
1133
1134
	delete(kvData, "general.name")
	delete(kvData, "tokenizer.chat_template")
	resp.ModelInfo = kvData

1135
1136
1137
1138
1139
1140
	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

1141
	if len(m.ProjectorPaths) > 0 {
1142
		projectorData, _, err := getModelData(m.ProjectorPaths[0], req.Verbose)
1143
1144
1145
1146
1147
1148
		if err != nil {
			return nil, err
		}
		resp.ProjectorInfo = projectorData
	}

Patrick Devine's avatar
Patrick Devine committed
1149
1150
1151
	return resp, nil
}

1152
func getModelData(digest string, verbose bool) (ggml.KV, ggml.Tensors, error) {
1153
1154
1155
1156
	maxArraySize := 0
	if verbose {
		maxArraySize = -1
	}
1157
	data, err := llm.LoadModel(digest, maxArraySize)
1158
	if err != nil {
1159
		return nil, ggml.Tensors{}, err
1160
1161
	}

1162
	kv := data.KV()
1163
1164
1165
1166
1167
1168
1169
1170
1171

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

1172
	return kv, data.Tensors(), nil
1173
1174
}

1175
func (s *Server) ListHandler(c *gin.Context) {
1176
	ms, err := Manifests(true)
Patrick Devine's avatar
Patrick Devine committed
1177
1178
1179
1180
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
1181

1182
	models := []api.ListModelResponse{}
1183
1184
	for n, m := range ms {
		var cf ConfigV2
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197

		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
1198
		}
Michael Yang's avatar
Michael Yang committed
1199

1200
1201
		// tag should never be masked
		models = append(models, api.ListModelResponse{
1202
1203
1204
1205
1206
1207
1208
			Model:       n.DisplayShortest(),
			Name:        n.DisplayShortest(),
			RemoteModel: cf.RemoteModel,
			RemoteHost:  cf.RemoteHost,
			Size:        m.Size(),
			Digest:      m.digest,
			ModifiedAt:  m.fi.ModTime(),
1209
1210
1211
1212
1213
1214
1215
			Details: api.ModelDetails{
				Format:            cf.ModelFormat,
				Family:            cf.ModelFamily,
				Families:          cf.ModelFamilies,
				ParameterSize:     cf.ModelType,
				QuantizationLevel: cf.FileType,
			},
1216
		})
Patrick Devine's avatar
Patrick Devine committed
1217
1218
	}

1219
	slices.SortStableFunc(models, func(i, j api.ListModelResponse) int {
1220
1221
1222
1223
		// most recently modified first
		return cmp.Compare(j.ModifiedAt.Unix(), i.ModifiedAt.Unix())
	})

Michael Yang's avatar
Michael Yang committed
1224
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
1225
1226
}

1227
func (s *Server) CopyHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1228
1229
	var r api.CopyRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
1230
1231
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
1232
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
1233
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Patrick Devine's avatar
Patrick Devine committed
1234
1235
1236
		return
	}

Michael Yang's avatar
Michael Yang committed
1237
1238
	src := model.ParseName(r.Source)
	if !src.IsValid() {
Michael Yang's avatar
Michael Yang committed
1239
1240
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("source %q is invalid", r.Source)})
		return
1241
	}
1242
1243
1244
1245
1246
	src, err := getExistingName(src)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
1247

Michael Yang's avatar
Michael Yang committed
1248
1249
	dst := model.ParseName(r.Destination)
	if !dst.IsValid() {
1250
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("destination %q is invalid", r.Destination)})
Patrick Devine's avatar
Patrick Devine committed
1251
1252
		return
	}
1253
1254
	dst, err = getExistingName(dst)
	if err != nil {
1255
1256
1257
1258
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
1259
1260
1261
1262
1263
	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
1264
1265
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1266
func (s *Server) HeadBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
	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
1278
	c.Status(http.StatusOK)
Michael Yang's avatar
Michael Yang committed
1279
1280
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1281
func (s *Server) CreateBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1282
1283
	if ib, ok := intermediateBlobs[c.Param("digest")]; ok {
		p, err := GetBlobsPath(ib)
1284
1285
1286
1287
1288
1289
		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
1290
1291
			slog.Info("evicting intermediate blob which no longer exists", "digest", ib)
			delete(intermediateBlobs, c.Param("digest"))
1292
1293
1294
1295
1296
1297
1298
1299
1300
		} else if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		} else {
			c.Status(http.StatusOK)
			return
		}
	}

1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
	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
	}

1319
	layer, err := NewLayer(c.Request.Body, "")
Michael Yang's avatar
Michael Yang committed
1320
1321
1322
1323
1324
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

1325
1326
	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
1327
1328
1329
		return
	}

Michael Yang's avatar
Michael Yang committed
1330
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
1331
1332
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
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
}

1354
func allowedHost(host string) bool {
1355
1356
	host = strings.ToLower(host)

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1357
	if host == "" || host == "localhost" {
1358
1359
1360
		return true
	}

1361
	if hostname, err := os.Hostname(); err == nil && host == strings.ToLower(hostname) {
1362
1363
1364
		return true
	}

Michael Yang's avatar
lint  
Michael Yang committed
1365
	tlds := []string{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1366
1367
1368
		"localhost",
		"local",
		"internal",
1369
	}
1370

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1371
	// check if the host is a local TLD
1372
1373
1374
1375
1376
1377
	for _, tld := range tlds {
		if strings.HasSuffix(host, "."+tld) {
			return true
		}
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1378
	return false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1379
}
1380

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1381
1382
1383
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
	return func(c *gin.Context) {
		if addr == nil {
1384
1385
1386
1387
			c.Next()
			return
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1388
		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
1389
1390
1391
1392
1393
1394
1395
1396
1397
			c.Next()
			return
		}

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1398
		if addr, err := netip.ParseAddr(host); err == nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1399
			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1400
1401
1402
1403
1404
				c.Next()
				return
			}
		}

1405
		if allowedHost(host) {
Michael Yang's avatar
lint  
Michael Yang committed
1406
			if c.Request.Method == http.MethodOptions {
1407
1408
1409
1410
				c.AbortWithStatus(http.StatusNoContent)
				return
			}

1411
1412
1413
1414
1415
1416
			c.Next()
			return
		}

		c.AbortWithStatus(http.StatusForbidden)
	}
1417
}
1418

1419
func (s *Server) GenerateRoutes(rc *ollama.Registry) (http.Handler, error) {
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
	corsConfig := cors.DefaultConfig()
	corsConfig.AllowWildcard = true
	corsConfig.AllowBrowserExtensions = true
	corsConfig.AllowHeaders = []string{
		"Authorization",
		"Content-Type",
		"User-Agent",
		"Accept",
		"X-Requested-With",

		// OpenAI compatibility headers
1431
1432
1433
1434
1435
		"OpenAI-Beta",
		"x-stainless-arch",
		"x-stainless-async",
		"x-stainless-custom-poll-interval",
		"x-stainless-helper-method",
1436
1437
		"x-stainless-lang",
		"x-stainless-os",
1438
1439
		"x-stainless-package-version",
		"x-stainless-poll-helper",
1440
1441
1442
1443
1444
1445
		"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
1446

Bruce MacDonald's avatar
Bruce MacDonald committed
1447
	r := gin.Default()
1448
	r.HandleMethodNotAllowed = true
1449
	r.Use(
1450
		cors.New(corsConfig),
1451
		allowedHostsMiddleware(s.addr),
1452
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
1453

1454
1455
1456
1457
1458
1459
	// 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}) })

1460
	// Local model cache management (new implementation is at end of function)
1461
1462
	r.POST("/api/pull", s.PullHandler)
	r.POST("/api/push", s.PushHandler)
1463
1464
	r.HEAD("/api/tags", s.ListHandler)
	r.GET("/api/tags", s.ListHandler)
1465
	r.POST("/api/show", s.ShowHandler)
1466
	r.DELETE("/api/delete", s.DeleteHandler)
1467

1468
1469
	r.POST("/api/me", s.WhoamiHandler)

1470
1471
1472
1473
	r.POST("/api/signout", s.SignoutHandler)
	// deprecated
	r.DELETE("/api/user/keys/:encodedKey", s.SignoutHandler)

1474
1475
	// Create
	r.POST("/api/create", s.CreateHandler)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1476
1477
	r.POST("/api/blobs/:digest", s.CreateBlobHandler)
	r.HEAD("/api/blobs/:digest", s.HeadBlobHandler)
1478
1479
1480
	r.POST("/api/copy", s.CopyHandler)

	// Inference
1481
	r.GET("/api/ps", s.PsHandler)
1482
1483
1484
1485
	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
1486

1487
	// Inference (OpenAI compatibility)
1488
1489
1490
1491
1492
	r.POST("/v1/chat/completions", middleware.ChatMiddleware(), s.ChatHandler)
	r.POST("/v1/completions", middleware.CompletionsMiddleware(), s.GenerateHandler)
	r.POST("/v1/embeddings", middleware.EmbeddingsMiddleware(), s.EmbedHandler)
	r.GET("/v1/models", middleware.ListMiddleware(), s.ListHandler)
	r.GET("/v1/models/:model", middleware.RetrieveMiddleware(), s.ShowHandler)
1493

1494
1495
1496
1497
1498
1499
	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,
1500

1501
1502
1503
			Prune: PruneLayers,
		}
		return rs, nil
1504
1505
	}

1506
	return r, nil
1507
1508
1509
}

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

1513
1514
1515
1516
1517
1518
1519
1520
	blobsDir, err := GetBlobsPath("")
	if err != nil {
		return err
	}
	if err := fixBlobs(blobsDir); err != nil {
		return err
	}

Michael Yang's avatar
bool  
Michael Yang committed
1521
	if !envconfig.NoPrune() {
1522
1523
1524
1525
1526
1527
1528
		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
			}
1529

1530
1531
1532
1533
			manifestsPath, err := GetManifestPath()
			if err != nil {
				return err
			}
1534

1535
1536
1537
			if err := PruneDirectory(manifestsPath); err != nil {
				return err
			}
1538
1539
1540
		}
	}

1541
1542
	s := &Server{addr: ln.Addr()}

1543
1544
1545
1546
1547
1548
1549
	var rc *ollama.Registry
	if useClient2 {
		var err error
		rc, err = ollama.DefaultRegistry()
		if err != nil {
			return err
		}
1550
1551
	}

1552
	h, err := s.GenerateRoutes(rc)
1553
1554
1555
	if err != nil {
		return err
	}
1556

1557
1558
	http.Handle("/", h)

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1559
	ctx, done := context.WithCancel(context.Background())
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1560
1561
	schedCtx, schedDone := context.WithCancel(ctx)
	sched := InitScheduler(schedCtx)
1562
	s.sched = sched
1563

1564
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1565
	srvr := &http.Server{
1566
1567
1568
1569
1570
1571
1572
1573
1574
		// 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
1575
1576
	}

1577
1578
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
1579
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
1580
1581
	go func() {
		<-signals
1582
		srvr.Close()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1583
		schedDone()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1584
		sched.unloadAllRunners()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1585
		done()
1586
1587
	}()

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1588
	s.sched.Run(schedCtx)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1589

1590
1591
1592
1593
	// 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
1594
1595
	// 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
1596
1597
	gpus := discover.GPUDevices(ctx, nil)
	discover.LogDetails(gpus)
1598

1599
1600
1601
1602
1603
1604
1605
1606
1607
	var totalVRAM uint64
	for _, gpu := range gpus {
		totalVRAM += gpu.TotalMemory - envconfig.GpuOverhead()
	}
	if totalVRAM < lowVRAMThreshold {
		s.lowVRAM = true
		slog.Info("entering low vram mode", "total vram", format.HumanBytes2(totalVRAM), "threshold", format.HumanBytes2(lowVRAMThreshold))
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1608
1609
1610
1611
1612
1613
1614
	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()
1615
	return nil
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1616
}
Michael Yang's avatar
Michael Yang committed
1617

1618
func waitForStream(c *gin.Context, ch chan any) {
1619
	c.Header("Content-Type", "application/json")
1620
	var latest api.ProgressResponse
1621
1622
1623
	for resp := range ch {
		switch r := resp.(type) {
		case api.ProgressResponse:
1624
			latest = r
1625
		case gin.H:
Josh's avatar
Josh committed
1626
1627
1628
1629
			status, ok := r["status"].(int)
			if !ok {
				status = http.StatusInternalServerError
			}
1630
1631
1632
			errorMsg, ok := r["error"].(string)
			if !ok {
				errorMsg = "unknown error"
1633
			}
1634
1635
			c.JSON(status, gin.H{"error": errorMsg})
			return
1636
		default:
1637
			c.JSON(http.StatusInternalServerError, gin.H{"error": "unknown message type"})
1638
1639
1640
			return
		}
	}
1641
1642

	c.JSON(http.StatusOK, latest)
1643
1644
}

Michael Yang's avatar
Michael Yang committed
1645
func streamResponse(c *gin.Context, ch chan any) {
1646
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
1647
1648
1649
1650
1651
1652
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
		// errors are provided as a gin.H with an "error" field and
		// an optional "status" field.  For errors that are streamed
		// before any content, we need to set the status code and
		// content type for the error.
		if h, ok := val.(gin.H); ok {
			if e, ok := h["error"].(string); ok {
				status, ok := h["status"].(int)
				if !ok {
					status = http.StatusInternalServerError
				}

				if !c.Writer.Written() {
					c.Header("Content-Type", "application/json")
					c.JSON(status, gin.H{"error": e})
				} else {
					if err := json.NewEncoder(c.Writer).Encode(gin.H{"error": e}); err != nil {
						slog.Error("streamResponse failed to encode json error", "error", err)
					}
				}

				return false
			}
		}

Michael Yang's avatar
Michael Yang committed
1677
1678
		bts, err := json.Marshal(val)
		if err != nil {
1679
			slog.Info(fmt.Sprintf("streamResponse: json.Marshal failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1680
1681
1682
			return false
		}

1683
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
1684
1685
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
1686
			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1687
1688
1689
1690
1691
1692
			return false
		}

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

1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
func (s *Server) WhoamiHandler(c *gin.Context) {
	// todo allow other hosts
	u, err := url.Parse("https://ollama.com")
	if err != nil {
		slog.Error(err.Error())
		c.JSON(http.StatusInternalServerError, gin.H{"error": "URL parse error"})
		return
	}

	client := api.NewClient(u, http.DefaultClient)
	user, err := client.Whoami(c)
	if err != nil {
		slog.Error(err.Error())
	}
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721

	// user isn't signed in
	if user != nil && user.Name == "" {
		sURL, sErr := signinURL()
		if sErr != nil {
			slog.Error(sErr.Error())
			c.JSON(http.StatusInternalServerError, gin.H{"error": "error getting authorization details"})
			return
		}

		c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized", "signin_url": sURL})
		return
	}

1722
1723
1724
1725
	c.JSON(http.StatusOK, user)
}

func (s *Server) SignoutHandler(c *gin.Context) {
1726
1727
1728
1729
1730
1731
1732
1733
	pubKey, err := auth.GetPublicKey()
	if err != nil {
		slog.Error("couldn't get public key", "error", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "there was an error signing out"})
		return
	}

	encKey := base64.RawURLEncoding.EncodeToString([]byte(pubKey))
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743

	// todo allow other hosts
	u, err := url.Parse("https://ollama.com")
	if err != nil {
		slog.Error(err.Error())
		c.JSON(http.StatusInternalServerError, gin.H{"error": "URL parse error"})
		return
	}

	client := api.NewClient(u, http.DefaultClient)
1744
	err = client.Disconnect(c, encKey)
1745
	if err != nil {
1746
1747
1748
		var authError api.AuthorizationError
		if errors.As(err, &authError) {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "you are not currently signed in"})
1749
1750
1751
1752
1753
1754
1755
1756
1757
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": "there was an error signing out"})
		return
	}

	c.JSON(http.StatusOK, nil)
}

1758
func (s *Server) PsHandler(c *gin.Context) {
1759
	models := []api.ProcessModelResponse{}
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770

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

1771
		mr := api.ProcessModelResponse{
1772
1773
			Model:     model.ShortName,
			Name:      model.ShortName,
Jesse Gross's avatar
Jesse Gross committed
1774
1775
			Size:      int64(v.totalSize),
			SizeVRAM:  int64(v.vramSize),
1776
1777
1778
1779
			Digest:    model.Digest,
			Details:   modelDetails,
			ExpiresAt: v.expiresAt,
		}
1780
		if v.Options != nil {
Jesse Gross's avatar
Jesse Gross committed
1781
			mr.ContextLength = v.Options.NumCtx
1782
		}
1783
1784
1785
1786
1787
1788
1789
1790
		// 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)
		}

1791
1792
1793
		models = append(models, mr)
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1794
1795
1796
1797
1798
	slices.SortStableFunc(models, func(i, j api.ProcessModelResponse) int {
		// longest duration remaining listed first
		return cmp.Compare(j.ExpiresAt.Unix(), i.ExpiresAt.Unix())
	})

1799
	c.JSON(http.StatusOK, api.ProcessResponse{Models: models})
1800
1801
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1802
func (s *Server) ChatHandler(c *gin.Context) {
1803
1804
	checkpointStart := time.Now()

Bruce MacDonald's avatar
Bruce MacDonald committed
1805
	var req api.ChatRequest
Michael Yang's avatar
Michael Yang committed
1806
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1807
1808
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
1809
	} else if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1810
1811
1812
1813
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
	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
	}

	m, err := GetModel(req.Model)
	if err != nil {
		switch {
		case os.IsNotExist(err):
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
		case err.Error() == errtypes.InvalidModelNameErrMsg:
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
Patrick Devine's avatar
Patrick Devine committed
1835
		}
1836
1837
1838
1839
		return
	}

	// expire the runner
Michael Yang's avatar
Michael Yang committed
1840
	if len(req.Messages) == 0 && req.KeepAlive != nil && req.KeepAlive.Duration == 0 {
1841
		s.sched.expireRunner(m)
Patrick Devine's avatar
Patrick Devine committed
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852

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

1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
	if m.Config.RemoteHost != "" && m.Config.RemoteModel != "" {
		origModel := req.Model

		remoteURL, err := url.Parse(m.Config.RemoteHost)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		if !slices.Contains(envconfig.Remotes(), remoteURL.Hostname()) {
			slog.Info("remote model", "remotes", envconfig.Remotes(), "remoteURL", m.Config.RemoteHost, "hostname", remoteURL.Hostname())
			c.JSON(http.StatusBadRequest, gin.H{"error": "this server cannot run this remote model"})
			return
		}

		req.Model = m.Config.RemoteModel
		if req.Options == nil {
			req.Options = map[string]any{}
		}

		msgs := append(m.Messages, req.Messages...)
		if req.Messages[0].Role != "system" && m.System != "" {
			msgs = append([]api.Message{{Role: "system", Content: m.System}}, msgs...)
		}
		msgs = filterThinkTags(msgs, m)
		req.Messages = msgs

		for k, v := range m.Options {
			if _, ok := req.Options[k]; !ok {
				req.Options[k] = v
			}
		}

		fn := func(resp api.ChatResponse) error {
			resp.Model = origModel
			resp.RemoteModel = m.Config.RemoteModel
			resp.RemoteHost = m.Config.RemoteHost

			data, err := json.Marshal(resp)
			if err != nil {
				return err
			}

			if _, err = c.Writer.Write(append(data, '\n')); err != nil {
				return err
			}
			c.Writer.Flush()
			return nil
		}

		client := api.NewClient(remoteURL, http.DefaultClient)
		err = client.Chat(c, &req, fn)
		if err != nil {
1906
1907
1908
1909
1910
1911
			var authError api.AuthorizationError
			if errors.As(err, &authError) {
				sURL, sErr := signinURL()
				if sErr != nil {
					slog.Error(sErr.Error())
					c.JSON(http.StatusInternalServerError, gin.H{"error": "error getting authorization details"})
1912
1913
					return
				}
1914
1915
1916
1917
1918
1919
1920

				c.JSON(authError.StatusCode, gin.H{"error": "unauthorized", "signin_url": sURL})
				return
			}
			var apiError api.StatusError
			if errors.As(err, &apiError) {
				c.JSON(apiError.StatusCode, apiError)
1921
1922
				return
			}
1923
1924
1925
1926
1927
1928
1929
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		return
	}

1930
	caps := []model.Capability{model.CapabilityCompletion}
1931
	if len(req.Tools) > 0 {
1932
		caps = append(caps, model.CapabilityTools)
Michael Yang's avatar
tools  
Michael Yang committed
1933
	}
1934
1935

	modelCaps := m.Capabilities()
1936
	if slices.Contains(modelCaps, model.CapabilityThinking) {
1937
		caps = append(caps, model.CapabilityThinking)
1938
		if req.Think == nil {
1939
1940
			req.Think = &api.ThinkValue{Value: true}
		}
1941
1942
1943
1944
1945
	} else {
		if req.Think != nil && req.Think.Bool() {
			c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("%q does not support thinking", req.Model)})
			return
		}
1946
	}
Michael Yang's avatar
tools  
Michael Yang committed
1947

1948
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), caps, req.Options, req.KeepAlive)
Michael Yang's avatar
Michael Yang committed
1949
1950
	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
1951
		return
Michael Yang's avatar
Michael Yang committed
1952
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
1953
		handleScheduleError(c, req.Model, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
1954
1955
		return
	}
Michael Yang's avatar
Michael Yang committed
1956

1957
1958
	checkpointLoaded := time.Now()

Michael Yang's avatar
Michael Yang committed
1959
1960
	if len(req.Messages) == 0 {
		c.JSON(http.StatusOK, api.ChatResponse{
1961
			Model:      req.Model,
Michael Yang's avatar
Michael Yang committed
1962
1963
			CreatedAt:  time.Now().UTC(),
			Message:    api.Message{Role: "assistant"},
1964
1965
			Done:       true,
			DoneReason: "load",
Michael Yang's avatar
Michael Yang committed
1966
		})
1967
1968
1969
		return
	}

Michael Yang's avatar
Michael Yang committed
1970
	msgs := append(m.Messages, req.Messages...)
1971
	if req.Messages[0].Role != "system" && m.System != "" {
Michael Yang's avatar
Michael Yang committed
1972
		msgs = append([]api.Message{{Role: "system", Content: m.System}}, msgs...)
1973
	}
1974
	msgs = filterThinkTags(msgs, m)
1975

1976
1977
	if shouldUseHarmony(m) && m.Config.Parser == "" {
		m.Config.Parser = "harmony"
Devon Rifkin's avatar
Devon Rifkin committed
1978
1979
	}

1980
	var builtinParser parsers.Parser
1981
	processedTools := req.Tools
1982

1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
	if m.Config.Parser != "" {
		builtinParser = parsers.ParserForName(m.Config.Parser)
		if builtinParser != nil {
			// Determine last message for chat prefill
			var lastMessage *api.Message
			if len(msgs) > 0 {
				lastMessage = &msgs[len(msgs)-1]
			}
			// Initialize parser and get processed tools
			processedTools = builtinParser.Init(req.Tools, lastMessage)
1993
1994
1995
		}
	}

1996
1997
	truncate := req.Truncate == nil || *req.Truncate
	prompt, images, err := chatPrompt(c.Request.Context(), m, r.Tokenize, opts, msgs, processedTools, req.Think, truncate)
Michael Yang's avatar
Michael Yang committed
1998
	if err != nil {
1999
		slog.Error("chat prompt error", "error", err)
Michael Yang's avatar
Michael Yang committed
2000
2001
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
2002
2003
	}

2004
2005
	// If debug mode is enabled, return the rendered template instead of calling the model
	if req.DebugRenderOnly {
Devon Rifkin's avatar
Devon Rifkin committed
2006
		c.JSON(http.StatusOK, api.ChatResponse{
2007
2008
			Model:     req.Model,
			CreatedAt: time.Now().UTC(),
Devon Rifkin's avatar
Devon Rifkin committed
2009
			DebugInfo: &api.DebugInfo{
2010
2011
2012
2013
2014
2015
2016
				RenderedTemplate: prompt,
				ImageCount:       len(images),
			},
		})
		return
	}

2017
2018
	// Validate Think value: string values currently only allowed for harmony/gptoss models
	if req.Think != nil && req.Think.IsString() && m.Config.Parser != "harmony" {
2019
		c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("think value %q is not supported for this model", req.Think.String())})
Michael Yang's avatar
Michael Yang committed
2020
2021
2022
		return
	}

2023
2024
	var thinkingState *thinking.Parser
	openingTag, closingTag := thinking.InferTags(m.Template.Template)
2025
	if req.Think != nil && req.Think.Bool() && openingTag != "" && closingTag != "" {
2026
		thinkingState = &thinking.Parser{
Devon Rifkin's avatar
Devon Rifkin committed
2027
2028
			OpeningTag: openingTag,
			ClosingTag: closingTag,
2029
		}
2030
2031
2032
2033

		if strings.HasSuffix(strings.TrimSpace(prompt), openingTag) {
			thinkingState.AddContent(openingTag)
		}
2034
2035
	}

2036
	var toolParser *tools.Parser
2037
	if len(req.Tools) > 0 && (builtinParser == nil || !builtinParser.HasToolSupport()) {
2038
		toolParser = tools.NewParser(m.Template.Template, req.Tools)
2039
2040
	}

2041
2042
2043
2044
2045
2046
2047
	type structuredOutputsState int
	const (
		structuredOutputsState_None structuredOutputsState = iota
		structuredOutputsState_ReadyToApply
		structuredOutputsState_Applying
	)

Bruce MacDonald's avatar
Bruce MacDonald committed
2048
2049
2050
	ch := make(chan any)
	go func() {
		defer close(ch)
2051

2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
		structuredOutputsState := structuredOutputsState_None

		for {
			var tb strings.Builder

			currentFormat := req.Format
			// structured outputs via double request is enabled when:
			// 1. the model supports the thinking capability and
			// 2. it uses a built-in parser or our generic thinking parser

			// Note that the current approach does not work for (potential future)
			// non-thinking models that emit anything before actual content. This
			// current approach uses the transition from parsed thinking content to
			// parsed non-thinking content as the signal to turn constraining on

			if req.Format != nil && structuredOutputsState == structuredOutputsState_None && ((builtinParser != nil || thinkingState != nil) && slices.Contains(m.Capabilities(), model.CapabilityThinking)) {
				currentFormat = nil
Michael Yang's avatar
Michael Yang committed
2069
2070
			}

2071
2072
2073
			// sets up new context given parent context per request
			ctx, cancel := context.WithCancel(c.Request.Context())
			err := r.Completion(ctx, llm.CompletionRequest{
2074
2075
2076
2077
2078
2079
				Prompt:   prompt,
				Images:   images,
				Format:   currentFormat,
				Options:  opts,
				Shift:    req.Shift == nil || *req.Shift,
				Truncate: truncate,
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
			}, func(r llm.CompletionResponse) {
				res := api.ChatResponse{
					Model:     req.Model,
					CreatedAt: time.Now().UTC(),
					Message:   api.Message{Role: "assistant", Content: r.Content},
					Done:      r.Done,
					Metrics: api.Metrics{
						PromptEvalCount:    r.PromptEvalCount,
						PromptEvalDuration: r.PromptEvalDuration,
						EvalCount:          r.EvalCount,
						EvalDuration:       r.EvalDuration,
					},
				}
				if r.Done {
					res.DoneReason = r.DoneReason.String()
					res.TotalDuration = time.Since(checkpointStart)
					res.LoadDuration = checkpointLoaded.Sub(checkpointStart)
				}
Devon Rifkin's avatar
Devon Rifkin committed
2098

2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
				if builtinParser != nil {
					slog.Log(context.TODO(), logutil.LevelTrace, "builtin parser input", "parser", m.Config.Parser, "content", r.Content)

					content, thinking, toolCalls, err := builtinParser.Add(r.Content, r.Done)
					if err != nil {
						ch <- gin.H{"error": err.Error()}
						return
					}

					res.Message.Content = content
					res.Message.Thinking = thinking
					res.Message.ToolCalls = toolCalls

					tb.WriteString(thinking)
					// we are now receiving content from the model - we should start applying structured outputs
					if structuredOutputsState == structuredOutputsState_None && req.Format != nil && tb.String() != "" && res.Message.Content != "" {
						structuredOutputsState = structuredOutputsState_ReadyToApply
						cancel()
						return
					}

					if res.Message.Content != "" || res.Message.Thinking != "" || len(res.Message.ToolCalls) > 0 || r.Done {
						slog.Log(context.TODO(), logutil.LevelTrace, "builtin parser output", "parser", m.Config.Parser, "content", content, "thinking", thinking, "toolCalls", toolCalls, "done", r.Done)
						ch <- res
					} else {
						slog.Log(context.TODO(), logutil.LevelTrace, "builtin parser empty output", "parser", m.Config.Parser)
					}
Devon Rifkin's avatar
Devon Rifkin committed
2126
2127
2128
					return
				}

2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
				if thinkingState != nil {
					thinkingContent, remainingContent := thinkingState.AddContent(res.Message.Content)
					if thinkingContent == "" && remainingContent == "" && !r.Done {
						// need to accumulate more to decide what to send
						return
					}
					res.Message.Thinking = thinkingContent
					tb.WriteString(thinkingContent)
					// emit the collected thinking text before restarting with structured outputs and clear unstructured content
					// to avoid leaking mixed tokens like "</think>Hello"
					if structuredOutputsState == structuredOutputsState_None && req.Format != nil && tb.String() != "" && remainingContent != "" {
						structuredOutputsState = structuredOutputsState_ReadyToApply
						res.Message.Content = ""
						ch <- res
						cancel()
						return
					}
					res.Message.Content = remainingContent
Devon Rifkin's avatar
Devon Rifkin committed
2147
2148
				}

2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
				if len(req.Tools) > 0 {
					toolCalls, content := toolParser.Add(res.Message.Content)
					if len(content) > 0 {
						res.Message.Content = content
					} else if len(toolCalls) > 0 {
						res.Message.ToolCalls = toolCalls
						res.Message.Content = ""
					} else if res.Message.Thinking != "" {
						// don't return
					} else {
						if r.Done {
							res.Message.Content = toolParser.Content()
							ch <- res
						}
						return
					}
				}
2166

2167
2168
2169
2170
2171
2172
				ch <- res
			})
			if err != nil {
				if structuredOutputsState == structuredOutputsState_ReadyToApply && strings.Contains(err.Error(), "context canceled") && c.Request.Context().Err() == nil {
					// only ignores error if it's a context cancellation due to setting structured outputs
				} else {
2173
2174
2175
2176
2177
2178
					var serr api.StatusError
					if errors.As(err, &serr) {
						ch <- gin.H{"error": serr.ErrorMessage, "status": serr.StatusCode}
					} else {
						ch <- gin.H{"error": err.Error()}
					}
2179
2180
2181
2182
					return
				}
			}

2183
2184
2185
2186
2187
2188
2189
2190
2191
			// ignored structured outputs cancellation falls through to here, start a new request with the structured outputs and updated prompt. use the
			if structuredOutputsState == structuredOutputsState_ReadyToApply {
				structuredOutputsState = structuredOutputsState_Applying
				msg := api.Message{
					Role:     "assistant",
					Thinking: tb.String(),
				}

				msgs = append(msgs, msg)
2192
				prompt, _, err = chatPrompt(c.Request.Context(), m, r.Tokenize, opts, msgs, processedTools, req.Think, truncate)
2193
2194
2195
				if err != nil {
					slog.Error("chat prompt error applying structured outputs", "error", err)
					ch <- gin.H{"error": err.Error()}
2196
					return
2197
				}
2198
2199
2200
2201
2202
2203
2204
2205
				// force constraining by terminating thinking header, the parser is already at this state
				// when the last message is thinking, the rendered for gpt-oss cannot disambiguate between having the
				// model continue thinking or ending thinking and outputting the final message.
				// TODO(parthsareen): consider adding prefill disambiguation logic to the renderer for structured outputs.
				if shouldUseHarmony(m) || (builtinParser != nil && m.Config.Parser == "harmony") {
					prompt += "<|end|><|start|>assistant<|channel|>final<|message|>"
				}
				continue
2206
			}
2207

2208
			break
Bruce MacDonald's avatar
Bruce MacDonald committed
2209
2210
2211
2212
		}
	}()

	if req.Stream != nil && !*req.Stream {
Michael Yang's avatar
tools  
Michael Yang committed
2213
		var resp api.ChatResponse
2214
		var toolCalls []api.ToolCall
2215
2216
		var sbThinking strings.Builder
		var sbContent strings.Builder
Michael Yang's avatar
Michael Yang committed
2217
2218
		for rr := range ch {
			switch t := rr.(type) {
2219
			case api.ChatResponse:
2220
2221
				sbThinking.WriteString(t.Message.Thinking)
				sbContent.WriteString(t.Message.Content)
Michael Yang's avatar
tools  
Michael Yang committed
2222
				resp = t
2223
2224
2225
				if len(req.Tools) > 0 {
					toolCalls = append(toolCalls, t.Message.ToolCalls...)
				}
2226
2227
2228
2229
2230
2231
			case gin.H:
				msg, ok := t["error"].(string)
				if !ok {
					msg = "unexpected error format in response"
				}

2232
2233
2234
2235
2236
2237
				status, ok := t["status"].(int)
				if !ok {
					status = http.StatusInternalServerError
				}

				c.JSON(status, gin.H{"error": msg})
Michael Yang's avatar
Michael Yang committed
2238
				return
2239
			default:
Michael Yang's avatar
Michael Yang committed
2240
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
2241
				return
Bruce MacDonald's avatar
Bruce MacDonald committed
2242
2243
			}
		}
2244

2245
2246
2247
		resp.Message.Content = sbContent.String()
		resp.Message.Thinking = sbThinking.String()

2248
2249
		if len(toolCalls) > 0 {
			resp.Message.ToolCalls = toolCalls
Michael Yang's avatar
tools  
Michael Yang committed
2250
2251
2252
		}

		c.JSON(http.StatusOK, resp)
Bruce MacDonald's avatar
Bruce MacDonald committed
2253
2254
2255
2256
2257
		return
	}

	streamResponse(c, ch)
}
2258

Michael Yang's avatar
Michael Yang committed
2259
func handleScheduleError(c *gin.Context, name string, err error) {
Michael Yang's avatar
Michael Yang committed
2260
	switch {
2261
	case errors.Is(err, errCapabilities), errors.Is(err, errRequired):
Michael Yang's avatar
Michael Yang committed
2262
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
2263
	case errors.Is(err, context.Canceled):
2264
		c.JSON(499, gin.H{"error": "request canceled"})
Michael Yang's avatar
Michael Yang committed
2265
	case errors.Is(err, ErrMaxQueue):
2266
		c.JSON(http.StatusServiceUnavailable, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
2267
2268
	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
2269
2270
	default:
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
2271
2272
	}
}
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284

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 {
2285
2286
2287
2288
2289
				// 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.
2290
				thinkingState := &thinking.Parser{
Devon Rifkin's avatar
Devon Rifkin committed
2291
2292
					OpeningTag: "<think>",
					ClosingTag: "</think>",
2293
				}
Devon Rifkin's avatar
Devon Rifkin committed
2294
				_, content := thinkingState.AddContent(msg.Content)
2295
				msgs[i].Content = content
2296
2297
2298
2299
2300
			}
		}
	}
	return msgs
}