routes.go 50.1 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"
33
	"github.com/ollama/ollama/format"
Michael Yang's avatar
Michael Yang committed
34
	"github.com/ollama/ollama/fs/ggml"
35
	"github.com/ollama/ollama/harmony"
36
	"github.com/ollama/ollama/llm"
37
	"github.com/ollama/ollama/logutil"
Devon Rifkin's avatar
Devon Rifkin committed
38
	"github.com/ollama/ollama/model/parsers"
39
	"github.com/ollama/ollama/openai"
40
41
	"github.com/ollama/ollama/server/internal/client/ollama"
	"github.com/ollama/ollama/server/internal/registry"
Michael Yang's avatar
Michael Yang committed
42
	"github.com/ollama/ollama/template"
43
	"github.com/ollama/ollama/thinking"
44
	"github.com/ollama/ollama/tools"
45
	"github.com/ollama/ollama/types/errtypes"
Michael Yang's avatar
Michael Yang committed
46
	"github.com/ollama/ollama/types/model"
47
	"github.com/ollama/ollama/version"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
48
49
)

50
51
52
53
54
55
56
57
58
59
60
61
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
}

62
63
64
65
66
67
func experimentEnabled(name string) bool {
	return slices.Contains(strings.Split(os.Getenv("OLLAMA_EXPERIMENT"), ","), name)
}

var useClient2 = experimentEnabled("client2")

68
69
70
71
// 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
72
73
var mode string = gin.DebugMode

74
type Server struct {
75
76
77
	addr    net.Addr
	sched   *Scheduler
	lowVRAM bool
78
79
}

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

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

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

Michael Yang's avatar
Michael Yang committed
117
	model, err := GetModel(name)
Bruce MacDonald's avatar
Bruce MacDonald committed
118
	if err != nil {
Michael Yang's avatar
Michael Yang committed
119
		return nil, nil, nil, err
120
121
	}

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

Michael Yang's avatar
Michael Yang committed
130
	opts, err := modelOptions(model, requestOpts)
131
	if err != nil {
Michael Yang's avatar
Michael Yang committed
132
		return nil, nil, nil, err
133
134
	}

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

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

Michael Yang's avatar
Michael Yang committed
149
	return runner.llama, model, &opts, nil
Michael Yang's avatar
Michael Yang committed
150
151
152
}

func (s *Server) GenerateHandler(c *gin.Context) {
153
	checkpointStart := time.Now()
Michael Yang's avatar
Michael Yang committed
154
155
156
157
158
159
	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
160
161
162
		return
	}

163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
	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
	}

179
	m, err := GetModel(name.String())
180
181
	if err != nil {
		switch {
182
		case errors.Is(err, fs.ErrNotExist):
183
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
184
		case err.Error() == errtypes.InvalidModelNameErrMsg:
185
186
187
188
189
190
191
			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
192
	// expire the runner
Michael Yang's avatar
Michael Yang committed
193
	if req.Prompt == "" && req.KeepAlive != nil && req.KeepAlive.Duration == 0 {
194
		s.sched.expireRunner(m)
Patrick Devine's avatar
Patrick Devine committed
195
196
197
198
199
200
201
202
203
204
205

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

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

211
212
213
	useHarmony := shouldUseHarmony(m) && !req.Raw
	var harmonyMessageHandler *harmony.HarmonyMessageHandler
	var harmonyToolParser *harmony.HarmonyToolCallAccumulator
Michael Yang's avatar
Michael Yang committed
214
	if useHarmony {
215
216
217
		harmonyMessageHandler = harmony.NewHarmonyMessageHandler()
		harmonyMessageHandler.HarmonyParser.AddImplicitStart()
		harmonyToolParser = harmonyMessageHandler.CreateToolParser()
Michael Yang's avatar
Michael Yang committed
218
219
220
221
	}

	// Validate Think value: string values currently only allowed for gptoss models
	if req.Think != nil && req.Think.IsString() && !useHarmony {
222
		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
223
224
225
		return
	}

226
	caps := []model.Capability{model.CapabilityCompletion}
227
	if req.Suffix != "" {
228
		caps = append(caps, model.CapabilityInsert)
229
	}
230
	if req.Think != nil && req.Think.Bool() {
231
232
233
234
235
236
		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
	}
237

238
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), caps, req.Options, req.KeepAlive)
Michael Yang's avatar
Michael Yang committed
239
240
241
242
	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
243
244
245
246
		handleScheduleError(c, req.Model, err)
		return
	}

247
248
	checkpointLoaded := time.Now()

249
	// load the model
Michael Yang's avatar
Michael Yang committed
250
251
252
253
254
255
256
	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
257
258
		return
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
259

260
261
	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"})
262
263
264
		return
	}

Michael Yang's avatar
Michael Yang committed
265
266
	images := make([]llm.ImageData, len(req.Images))
	for i := range req.Images {
267
		images[i] = llm.ImageData{ID: i, Data: req.Images[i]}
Michael Yang's avatar
Michael Yang committed
268
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
269

Michael Yang's avatar
Michael Yang committed
270
271
	prompt := req.Prompt
	if !req.Raw {
Michael Yang's avatar
Michael Yang committed
272
		tmpl := m.Template
Michael Yang's avatar
Michael Yang committed
273
274
275
276
277
278
279
280
		if req.Template != "" {
			tmpl, err = template.Parse(req.Template)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}

281
282
283
284
285
286
287
288
289
290
291
292
		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
293
294
295
296
			if req.Context == nil {
				msgs = append(msgs, m.Messages...)
			}

297
			for _, i := range images {
298
299
				imgPrompt := ""
				msgs = append(msgs, api.Message{Role: "user", Content: fmt.Sprintf("[img-%d]"+imgPrompt, i.ID)})
300
301
302
303
304
			}

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

305
		values.Think = req.Think != nil && req.Think.Bool()
Michael Yang's avatar
Michael Yang committed
306
307
		values.ThinkLevel = ""
		if req.Think != nil {
308
			values.ThinkLevel = req.Think.String()
Michael Yang's avatar
Michael Yang committed
309
		}
310
311
		values.IsThinkSet = req.Think != nil

Michael Yang's avatar
Michael Yang committed
312
313
		var b bytes.Buffer
		if req.Context != nil {
314
			slog.Warn("the context field is deprecated and will be removed in a future version of Ollama")
315
			s, err := r.Detokenize(c.Request.Context(), req.Context)
Michael Yang's avatar
Michael Yang committed
316
317
318
319
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
320
			b.WriteString(s)
Michael Yang's avatar
Michael Yang committed
321
		}
322
323
324
325
326
327
328

		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
329
330
	}

331
332
	// If debug mode is enabled, return the rendered template instead of calling the model
	if req.DebugRenderOnly {
Devon Rifkin's avatar
Devon Rifkin committed
333
		c.JSON(http.StatusOK, api.GenerateResponse{
334
335
			Model:     req.Model,
			CreatedAt: time.Now().UTC(),
Devon Rifkin's avatar
Devon Rifkin committed
336
			DebugInfo: &api.DebugInfo{
337
338
339
340
341
342
343
				RenderedTemplate: prompt,
				ImageCount:       len(images),
			},
		})
		return
	}

344
	var thinkingState *thinking.Parser
Michael Yang's avatar
Michael Yang committed
345
346
	if !useHarmony {
		openingTag, closingTag := thinking.InferTags(m.Template.Template)
347
		if req.Think != nil && req.Think.Bool() && openingTag != "" && closingTag != "" {
Michael Yang's avatar
Michael Yang committed
348
349
350
351
			thinkingState = &thinking.Parser{
				OpeningTag: openingTag,
				ClosingTag: closingTag,
			}
352
353
354
		}
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
355
356
	ch := make(chan any)
	go func() {
357
358
		// TODO (jmorganca): avoid building the response twice both here and below
		var sb strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
359
		defer close(ch)
Michael Yang's avatar
Michael Yang committed
360
		if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
361
362
363
364
			Prompt:  prompt,
			Images:  images,
			Format:  req.Format,
			Options: opts,
365
366
		}, func(cr llm.CompletionResponse) {
			res := api.GenerateResponse{
367
368
369
370
				Model:     req.Model,
				CreatedAt: time.Now().UTC(),
				Response:  cr.Content,
				Done:      cr.Done,
Bruce MacDonald's avatar
Bruce MacDonald committed
371
				Metrics: api.Metrics{
372
373
374
375
					PromptEvalCount:    cr.PromptEvalCount,
					PromptEvalDuration: cr.PromptEvalDuration,
					EvalCount:          cr.EvalCount,
					EvalDuration:       cr.EvalDuration,
Bruce MacDonald's avatar
Bruce MacDonald committed
376
				},
Bruce MacDonald's avatar
Bruce MacDonald committed
377
			}
378

Michael Yang's avatar
Michael Yang committed
379
			if useHarmony {
380
381
382
383
384
				content, thinking, toolContent := harmonyMessageHandler.AddContent(cr.Content, harmonyToolParser)
				res.Response = content
				res.Thinking = thinking
				harmonyToolParser.Add(toolContent)
			} else if thinkingState != nil {
Devon Rifkin's avatar
Devon Rifkin committed
385
				thinking, content := thinkingState.AddContent(cr.Content)
386
387
388
389
				res.Thinking = thinking
				res.Response = content
			}

390
391
392
393
394
			if _, err := sb.WriteString(cr.Content); err != nil {
				ch <- gin.H{"error": err.Error()}
			}

			if cr.Done {
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
				if useHarmony {
					toolName, toolContent := harmonyToolParser.Drain()
					if toolName != nil {
						*toolName = strings.TrimPrefix(*toolName, "functions.")
						var args api.ToolCallFunctionArguments
						if err := json.Unmarshal([]byte(toolContent), &args); err != nil {
							errStr := fmt.Sprintf("error parsing tool call: raw='%s', err=%s", toolContent, err.Error())
							ch <- gin.H{"error": errStr}
							return
						}

						res.ToolCalls = append(res.ToolCalls, api.ToolCall{
							Function: api.ToolCallFunction{
								Name:      *toolName,
								Arguments: args,
							},
						})
					}
				}

				res.DoneReason = cr.DoneReason.String()
				res.TotalDuration = time.Since(checkpointStart)
				res.LoadDuration = checkpointLoaded.Sub(checkpointStart)

419
				if !req.Raw {
420
					tokens, err := r.Tokenize(c.Request.Context(), prompt+sb.String())
421
422
423
424
					if err != nil {
						ch <- gin.H{"error": err.Error()}
						return
					}
425
					res.Context = tokens
426
427
428
				}
			}

Michael Yang's avatar
Michael Yang committed
429
430
431
432
433
434
435
436
437
			if useHarmony {
				// only send messages with meaningful content (empty messages confuse clients)
				if res.Response != "" || res.Thinking != "" || res.Done || len(res.ToolCalls) > 0 {
					ch <- res
				}

				return
			}

438
			ch <- res
Michael Yang's avatar
Michael Yang committed
439
		}); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
440
441
442
443
444
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
Michael Yang's avatar
Michael Yang committed
445
		var r api.GenerateResponse
446
447
		var sbThinking strings.Builder
		var sbContent strings.Builder
Michael Yang's avatar
Michael Yang committed
448
449
		for rr := range ch {
			switch t := rr.(type) {
450
			case api.GenerateResponse:
451
452
				sbThinking.WriteString(t.Thinking)
				sbContent.WriteString(t.Response)
Michael Yang's avatar
Michael Yang committed
453
				r = t
454
			case gin.H:
Michael Yang's avatar
Michael Yang committed
455
456
457
				msg, ok := t["error"].(string)
				if !ok {
					msg = "unexpected error format in response"
458
				}
Michael Yang's avatar
Michael Yang committed
459
460
461

				c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
				return
462
			default:
Michael Yang's avatar
Michael Yang committed
463
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
Bruce MacDonald's avatar
Bruce MacDonald committed
464
465
466
				return
			}
		}
467

468
469
470
		r.Thinking = sbThinking.String()
		r.Response = sbContent.String()

Michael Yang's avatar
Michael Yang committed
471
		c.JSON(http.StatusOK, r)
Bruce MacDonald's avatar
Bruce MacDonald committed
472
473
474
475
476
477
		return
	}

	streamResponse(c, ch)
}

478
func (s *Server) EmbedHandler(c *gin.Context) {
479
	checkpointStart := time.Now()
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
	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:
513
514
515
516
		if req.Input != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid input type"})
			return
		}
517
518
	}

519
520
521
522
523
524
	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
	}

525
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), []model.Capability{}, req.Options, req.KeepAlive)
526
527
528
529
530
	if err != nil {
		handleScheduleError(c, req.Model, err)
		return
	}

531
532
	checkpointLoaded := time.Now()

533
534
535
536
537
	if len(input) == 0 {
		c.JSON(http.StatusOK, api.EmbedResponse{Model: req.Model, Embeddings: [][]float32{}})
		return
	}

538
	kvData, _, err := getModelData(m.ModelPath, false)
539
540
541
542
543
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

544
	var count int
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
	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
			}
		}

567
568
		count += len(tokens)

569
570
		input[i] = s
	}
571
572
573
574
575
576
577
578
579

	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
			}
580
581
582
583
584
585
			// 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
586
587
			return nil
		})
588
589
	}

590
	if err := g.Wait(); err != nil {
591
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": strings.TrimSpace(err.Error())})
592
		return
593
594
595
	}

	resp := api.EmbedResponse{
596
		Model:           req.Model,
597
		Embeddings:      embeddings,
598
599
		TotalDuration:   time.Since(checkpointStart),
		LoadDuration:    checkpointLoaded.Sub(checkpointStart),
600
		PromptEvalCount: count,
601
602
603
604
605
606
607
608
609
610
	}
	c.JSON(http.StatusOK, resp)
}

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

611
	norm := float32(1.0 / max(math.Sqrt(float64(sum)), 1e-12))
612
613
614
615
616
617
	for i := range vec {
		vec[i] *= norm
	}
	return vec
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
618
func (s *Server) EmbeddingsHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
619
	var req api.EmbeddingRequest
Michael Yang's avatar
Michael Yang committed
620
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
Bruce MacDonald's avatar
Bruce MacDonald committed
621
622
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
623
	} else if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
624
625
626
627
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

628
629
630
631
632
633
	name := model.ParseName(req.Model)
	if !name.IsValid() {
		c.JSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
	}

634
	r, _, _, err := s.scheduleRunner(c.Request.Context(), name.String(), []model.Capability{}, req.Options, req.KeepAlive)
Bruce MacDonald's avatar
Bruce MacDonald committed
635
	if err != nil {
Michael Yang's avatar
Michael Yang committed
636
		handleScheduleError(c, req.Model, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
637
638
639
		return
	}

640
641
642
	// an empty request loads the model
	if req.Prompt == "" {
		c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: []float64{}})
Bruce MacDonald's avatar
Bruce MacDonald committed
643
644
645
		return
	}

646
	embedding, err := r.Embedding(c.Request.Context(), req.Prompt)
Bruce MacDonald's avatar
Bruce MacDonald committed
647
	if err != nil {
648
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": strings.TrimSpace(err.Error())})
Bruce MacDonald's avatar
Bruce MacDonald committed
649
650
651
		return
	}

652
653
654
	var e []float64
	for _, v := range embedding {
		e = append(e, float64(v))
655
656
657
	}

	resp := api.EmbeddingResponse{
658
		Embedding: e,
659
660
	}
	c.JSON(http.StatusOK, resp)
Bruce MacDonald's avatar
Bruce MacDonald committed
661
662
}

663
func (s *Server) PullHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
664
	var req api.PullRequest
Michael Yang's avatar
Michael Yang committed
665
666
667
668
669
670
671
	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
672
673
674
		return
	}

675
676
	name := model.ParseName(cmp.Or(req.Model, req.Name))
	if !name.IsValid() {
677
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": errtypes.InvalidModelNameErrMsg})
678
679
680
		return
	}

681
682
	name, err = getExistingName(name)
	if err != nil {
683
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
684
685
686
		return
	}

687
688
689
	ch := make(chan any)
	go func() {
		defer close(ch)
690
691
		fn := func(r api.ProgressResponse) {
			ch <- r
692
		}
693

Michael Yang's avatar
Michael Yang committed
694
		regOpts := &registryOptions{
695
696
697
			Insecure: req.Insecure,
		}

698
699
700
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

701
		if err := PullModel(ctx, name.DisplayShortest(), regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
702
			ch <- gin.H{"error": err.Error()}
703
704
705
		}
	}()

706
707
708
709
710
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

711
712
713
	streamResponse(c, ch)
}

714
func (s *Server) PushHandler(c *gin.Context) {
715
	var req api.PushRequest
Michael Yang's avatar
Michael Yang committed
716
717
718
719
720
721
722
	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
723
724
		return
	}
Michael Yang's avatar
Michael Yang committed
725

726
	var mname string
Michael Yang's avatar
Michael Yang committed
727
	if req.Model != "" {
728
		mname = req.Model
Michael Yang's avatar
Michael Yang committed
729
	} else if req.Name != "" {
730
		mname = req.Name
Michael Yang's avatar
Michael Yang committed
731
732
	} else {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
733
734
735
		return
	}

736
737
738
	ch := make(chan any)
	go func() {
		defer close(ch)
739
740
		fn := func(r api.ProgressResponse) {
			ch <- r
741
		}
742

Michael Yang's avatar
Michael Yang committed
743
		regOpts := &registryOptions{
744
745
746
			Insecure: req.Insecure,
		}

Michael Yang's avatar
Michael Yang committed
747
748
749
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

750
751
752
753
754
755
756
		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
757
			ch <- gin.H{"error": err.Error()}
758
759
760
		}
	}()

761
762
763
764
765
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

766
767
768
	streamResponse(c, ch)
}

769
770
771
772
// 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.
773
774
775
func getExistingName(n model.Name) (model.Name, error) {
	var zero model.Name
	existing, err := Manifests(true)
776
	if err != nil {
777
		return zero, err
778
	}
779
	var set model.Name // tracks parts already canonicalized
780
	for e := range existing {
781
782
783
784
785
786
787
788
789
790
791
		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
792
793
		}
	}
794
	return n, nil
795
796
}

797
func (s *Server) DeleteHandler(c *gin.Context) {
798
799
	var r api.DeleteRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
800
801
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
802
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
803
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
804
805
806
		return
	}

807
808
809
	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))})
810
811
		return
	}
Michael Yang's avatar
Michael Yang committed
812

813
814
815
816
817
818
	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
	}

819
	m, err := ParseNamedManifest(n)
Michael Yang's avatar
Michael Yang committed
820
	if err != nil {
821
822
823
824
825
826
		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
827
828
829
		return
	}

830
	if err := m.Remove(); err != nil {
Michael Yang's avatar
Michael Yang committed
831
832
833
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
834
835
836
837
838

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

841
func (s *Server) ShowHandler(c *gin.Context) {
Patrick Devine's avatar
Patrick Devine committed
842
	var req api.ShowRequest
Michael Yang's avatar
Michael Yang committed
843
844
845
846
847
848
849
	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
850
851
852
		return
	}

Michael Yang's avatar
Michael Yang committed
853
	if req.Model != "" {
Michael Yang's avatar
Michael Yang committed
854
		// noop
Michael Yang's avatar
Michael Yang committed
855
	} else if req.Name != "" {
Michael Yang's avatar
Michael Yang committed
856
		req.Model = req.Name
Michael Yang's avatar
Michael Yang committed
857
	} else {
858
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
859
860
861
		return
	}

862
	resp, err := GetModelInfo(req)
Patrick Devine's avatar
Patrick Devine committed
863
	if err != nil {
864
865
		switch {
		case os.IsNotExist(err):
Michael Yang's avatar
Michael Yang committed
866
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
867
		case err.Error() == errtypes.InvalidModelNameErrMsg:
868
869
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
Patrick Devine's avatar
Patrick Devine committed
870
871
872
873
874
875
876
877
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

	c.JSON(http.StatusOK, resp)
}

878
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
879
880
	name := model.ParseName(req.Model)
	if !name.IsValid() {
CYJiang's avatar
CYJiang committed
881
		return nil, ErrModelPathInvalid
882
883
884
885
886
887
888
	}
	name, err := getExistingName(name)
	if err != nil {
		return nil, err
	}

	m, err := GetModel(name.String())
Patrick Devine's avatar
Patrick Devine committed
889
890
891
892
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
893
	modelDetails := api.ModelDetails{
894
895
896
897
898
899
		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
900
901
	}

902
	if req.System != "" {
903
		m.System = req.System
904
905
	}

Michael Yang's avatar
Michael Yang committed
906
907
908
	msgs := make([]api.Message, len(m.Messages))
	for i, msg := range m.Messages {
		msgs[i] = api.Message{Role: msg.Role, Content: msg.Content}
909
910
	}

911
	manifest, err := ParseNamedManifest(name)
912
913
914
915
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
916
	resp := &api.ShowResponse{
917
918
919
920
921
922
923
		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
924
925
926
927
	}

	var params []string
	cs := 30
928
	for k, v := range m.Options {
Patrick Devine's avatar
Patrick Devine committed
929
		switch val := v.(type) {
930
		case []any:
Patrick Devine's avatar
Patrick Devine committed
931
			for _, nv := range val {
Patrick Devine's avatar
Patrick Devine committed
932
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
Patrick Devine's avatar
Patrick Devine committed
933
			}
Patrick Devine's avatar
Patrick Devine committed
934
935
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
Patrick Devine's avatar
Patrick Devine committed
936
937
938
939
		}
	}
	resp.Parameters = strings.Join(params, "\n")

Patrick Devine's avatar
Patrick Devine committed
940
941
942
943
944
	if len(req.Options) > 0 {
		if m.Options == nil {
			m.Options = make(map[string]any)
		}
		for k, v := range req.Options {
945
			m.Options[k] = v
946
947
948
		}
	}

949
	var sb strings.Builder
950
	fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"")
951
	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
952
953
	fmt.Fprintf(&sb, "# FROM %s\n\n", m.ShortName)
	fmt.Fprint(&sb, m.String())
954
	resp.Modelfile = sb.String()
955

956
	kvData, tensors, err := getModelData(m.ModelPath, req.Verbose)
957
958
959
	if err != nil {
		return nil, err
	}
960

961
962
963
964
	delete(kvData, "general.name")
	delete(kvData, "tokenizer.chat_template")
	resp.ModelInfo = kvData

965
966
967
968
969
970
	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

971
	if len(m.ProjectorPaths) > 0 {
972
		projectorData, _, err := getModelData(m.ProjectorPaths[0], req.Verbose)
973
974
975
976
977
978
		if err != nil {
			return nil, err
		}
		resp.ProjectorInfo = projectorData
	}

Patrick Devine's avatar
Patrick Devine committed
979
980
981
	return resp, nil
}

982
func getModelData(digest string, verbose bool) (ggml.KV, ggml.Tensors, error) {
983
984
985
986
	maxArraySize := 0
	if verbose {
		maxArraySize = -1
	}
987
	data, err := llm.LoadModel(digest, maxArraySize)
988
	if err != nil {
989
		return nil, ggml.Tensors{}, err
990
991
	}

992
	kv := data.KV()
993
994
995
996
997
998
999
1000
1001

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

1002
	return kv, data.Tensors(), nil
1003
1004
}

1005
func (s *Server) ListHandler(c *gin.Context) {
1006
	ms, err := Manifests(true)
Patrick Devine's avatar
Patrick Devine committed
1007
1008
1009
1010
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
1011

1012
	models := []api.ListModelResponse{}
1013
1014
	for n, m := range ms {
		var cf ConfigV2
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027

		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
1028
		}
Michael Yang's avatar
Michael Yang committed
1029

1030
1031
		// tag should never be masked
		models = append(models, api.ListModelResponse{
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
			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,
			},
1044
		})
Patrick Devine's avatar
Patrick Devine committed
1045
1046
	}

1047
	slices.SortStableFunc(models, func(i, j api.ListModelResponse) int {
1048
1049
1050
1051
		// most recently modified first
		return cmp.Compare(j.ModifiedAt.Unix(), i.ModifiedAt.Unix())
	})

Michael Yang's avatar
Michael Yang committed
1052
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
1053
1054
}

1055
func (s *Server) CopyHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1056
1057
	var r api.CopyRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
1058
1059
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
1060
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
1061
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Patrick Devine's avatar
Patrick Devine committed
1062
1063
1064
		return
	}

Michael Yang's avatar
Michael Yang committed
1065
1066
	src := model.ParseName(r.Source)
	if !src.IsValid() {
Michael Yang's avatar
Michael Yang committed
1067
1068
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("source %q is invalid", r.Source)})
		return
1069
	}
1070
1071
1072
1073
1074
	src, err := getExistingName(src)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
1075

Michael Yang's avatar
Michael Yang committed
1076
1077
	dst := model.ParseName(r.Destination)
	if !dst.IsValid() {
1078
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("destination %q is invalid", r.Destination)})
Patrick Devine's avatar
Patrick Devine committed
1079
1080
		return
	}
1081
1082
	dst, err = getExistingName(dst)
	if err != nil {
1083
1084
1085
1086
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
1087
1088
1089
1090
1091
	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
1092
1093
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1094
func (s *Server) HeadBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
	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
1106
	c.Status(http.StatusOK)
Michael Yang's avatar
Michael Yang committed
1107
1108
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1109
func (s *Server) CreateBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1110
1111
	if ib, ok := intermediateBlobs[c.Param("digest")]; ok {
		p, err := GetBlobsPath(ib)
1112
1113
1114
1115
1116
1117
		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
1118
1119
			slog.Info("evicting intermediate blob which no longer exists", "digest", ib)
			delete(intermediateBlobs, c.Param("digest"))
1120
1121
1122
1123
1124
1125
1126
1127
1128
		} else if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		} else {
			c.Status(http.StatusOK)
			return
		}
	}

1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
	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
	}

1147
	layer, err := NewLayer(c.Request.Body, "")
Michael Yang's avatar
Michael Yang committed
1148
1149
1150
1151
1152
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

1153
1154
	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
1155
1156
1157
		return
	}

Michael Yang's avatar
Michael Yang committed
1158
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
1159
1160
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
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
}

1182
func allowedHost(host string) bool {
1183
1184
	host = strings.ToLower(host)

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1185
	if host == "" || host == "localhost" {
1186
1187
1188
		return true
	}

1189
	if hostname, err := os.Hostname(); err == nil && host == strings.ToLower(hostname) {
1190
1191
1192
		return true
	}

Michael Yang's avatar
lint  
Michael Yang committed
1193
	tlds := []string{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1194
1195
1196
		"localhost",
		"local",
		"internal",
1197
	}
1198

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1199
	// check if the host is a local TLD
1200
1201
1202
1203
1204
1205
	for _, tld := range tlds {
		if strings.HasSuffix(host, "."+tld) {
			return true
		}
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1206
	return false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1207
}
1208

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1209
1210
1211
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
	return func(c *gin.Context) {
		if addr == nil {
1212
1213
1214
1215
			c.Next()
			return
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1216
		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
1217
1218
1219
1220
1221
1222
1223
1224
1225
			c.Next()
			return
		}

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1226
		if addr, err := netip.ParseAddr(host); err == nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1227
			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1228
1229
1230
1231
1232
				c.Next()
				return
			}
		}

1233
		if allowedHost(host) {
Michael Yang's avatar
lint  
Michael Yang committed
1234
			if c.Request.Method == http.MethodOptions {
1235
1236
1237
1238
				c.AbortWithStatus(http.StatusNoContent)
				return
			}

1239
1240
1241
1242
1243
1244
			c.Next()
			return
		}

		c.AbortWithStatus(http.StatusForbidden)
	}
1245
}
1246

1247
func (s *Server) GenerateRoutes(rc *ollama.Registry) (http.Handler, error) {
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
	corsConfig := cors.DefaultConfig()
	corsConfig.AllowWildcard = true
	corsConfig.AllowBrowserExtensions = true
	corsConfig.AllowHeaders = []string{
		"Authorization",
		"Content-Type",
		"User-Agent",
		"Accept",
		"X-Requested-With",

		// OpenAI compatibility headers
1259
1260
1261
1262
1263
		"OpenAI-Beta",
		"x-stainless-arch",
		"x-stainless-async",
		"x-stainless-custom-poll-interval",
		"x-stainless-helper-method",
1264
1265
		"x-stainless-lang",
		"x-stainless-os",
1266
1267
		"x-stainless-package-version",
		"x-stainless-poll-helper",
1268
1269
1270
1271
1272
1273
		"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
1274

Bruce MacDonald's avatar
Bruce MacDonald committed
1275
	r := gin.Default()
1276
	r.HandleMethodNotAllowed = true
1277
	r.Use(
1278
		cors.New(corsConfig),
1279
		allowedHostsMiddleware(s.addr),
1280
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
1281

1282
1283
1284
1285
1286
1287
	// 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}) })

1288
	// Local model cache management (new implementation is at end of function)
1289
1290
	r.POST("/api/pull", s.PullHandler)
	r.POST("/api/push", s.PushHandler)
1291
1292
	r.HEAD("/api/tags", s.ListHandler)
	r.GET("/api/tags", s.ListHandler)
1293
	r.POST("/api/show", s.ShowHandler)
1294
	r.DELETE("/api/delete", s.DeleteHandler)
1295
1296
1297

	// Create
	r.POST("/api/create", s.CreateHandler)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1298
1299
	r.POST("/api/blobs/:digest", s.CreateBlobHandler)
	r.HEAD("/api/blobs/:digest", s.HeadBlobHandler)
1300
1301
1302
	r.POST("/api/copy", s.CopyHandler)

	// Inference
1303
	r.GET("/api/ps", s.PsHandler)
1304
1305
1306
1307
	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
1308

1309
	// Inference (OpenAI compatibility)
1310
	r.POST("/v1/chat/completions", openai.ChatMiddleware(), s.ChatHandler)
1311
	r.POST("/v1/completions", openai.CompletionsMiddleware(), s.GenerateHandler)
1312
	r.POST("/v1/embeddings", openai.EmbeddingsMiddleware(), s.EmbedHandler)
1313
1314
	r.GET("/v1/models", openai.ListMiddleware(), s.ListHandler)
	r.GET("/v1/models/:model", openai.RetrieveMiddleware(), s.ShowHandler)
1315

1316
1317
1318
1319
1320
1321
	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,
1322

1323
1324
1325
			Prune: PruneLayers,
		}
		return rs, nil
1326
1327
	}

1328
	return r, nil
1329
1330
1331
}

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

1335
1336
1337
1338
1339
1340
1341
1342
	blobsDir, err := GetBlobsPath("")
	if err != nil {
		return err
	}
	if err := fixBlobs(blobsDir); err != nil {
		return err
	}

Michael Yang's avatar
bool  
Michael Yang committed
1343
	if !envconfig.NoPrune() {
1344
1345
1346
1347
1348
1349
1350
		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
			}
1351

1352
1353
1354
1355
			manifestsPath, err := GetManifestPath()
			if err != nil {
				return err
			}
1356

1357
1358
1359
			if err := PruneDirectory(manifestsPath); err != nil {
				return err
			}
1360
1361
1362
		}
	}

1363
1364
	s := &Server{addr: ln.Addr()}

1365
1366
1367
1368
1369
1370
1371
	var rc *ollama.Registry
	if useClient2 {
		var err error
		rc, err = ollama.DefaultRegistry()
		if err != nil {
			return err
		}
1372
1373
	}

1374
	h, err := s.GenerateRoutes(rc)
1375
1376
1377
	if err != nil {
		return err
	}
1378

1379
1380
	http.Handle("/", h)

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1381
	ctx, done := context.WithCancel(context.Background())
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1382
1383
	schedCtx, schedDone := context.WithCancel(ctx)
	sched := InitScheduler(schedCtx)
1384
	s.sched = sched
1385

1386
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1387
	srvr := &http.Server{
1388
1389
1390
1391
1392
1393
1394
1395
1396
		// 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
1397
1398
	}

1399
1400
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
1401
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
1402
1403
	go func() {
		<-signals
1404
		srvr.Close()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1405
		schedDone()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1406
		sched.unloadAllRunners()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1407
		done()
1408
1409
	}()

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1410
	s.sched.Run(schedCtx)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1411

1412
1413
1414
1415
	// 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
1416
1417
	// 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
1418
	gpus := discover.GetGPUInfo()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1419
	gpus.LogDetails()
1420

1421
1422
1423
1424
1425
1426
1427
1428
1429
	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
1430
1431
1432
1433
1434
1435
1436
	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()
1437
	return nil
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1438
}
Michael Yang's avatar
Michael Yang committed
1439

1440
func waitForStream(c *gin.Context, ch chan any) {
1441
	c.Header("Content-Type", "application/json")
1442
	var latest api.ProgressResponse
1443
1444
1445
	for resp := range ch {
		switch r := resp.(type) {
		case api.ProgressResponse:
1446
			latest = r
1447
		case gin.H:
Josh's avatar
Josh committed
1448
1449
1450
1451
			status, ok := r["status"].(int)
			if !ok {
				status = http.StatusInternalServerError
			}
1452
1453
1454
			errorMsg, ok := r["error"].(string)
			if !ok {
				errorMsg = "unknown error"
1455
			}
1456
1457
			c.JSON(status, gin.H{"error": errorMsg})
			return
1458
		default:
1459
			c.JSON(http.StatusInternalServerError, gin.H{"error": "unknown message type"})
1460
1461
1462
			return
		}
	}
1463
1464

	c.JSON(http.StatusOK, latest)
1465
1466
}

Michael Yang's avatar
Michael Yang committed
1467
func streamResponse(c *gin.Context, ch chan any) {
1468
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
1469
1470
1471
1472
1473
1474
1475
1476
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

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

1481
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
1482
1483
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
1484
			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1485
1486
1487
1488
1489
1490
			return false
		}

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

1492
func (s *Server) PsHandler(c *gin.Context) {
1493
	models := []api.ProcessModelResponse{}
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504

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

1505
		mr := api.ProcessModelResponse{
1506
1507
			Model:     model.ShortName,
			Name:      model.ShortName,
Jesse Gross's avatar
Jesse Gross committed
1508
1509
			Size:      int64(v.totalSize),
			SizeVRAM:  int64(v.vramSize),
1510
1511
1512
1513
			Digest:    model.Digest,
			Details:   modelDetails,
			ExpiresAt: v.expiresAt,
		}
1514
		if v.Options != nil {
Jesse Gross's avatar
Jesse Gross committed
1515
			mr.ContextLength = v.Options.NumCtx
1516
		}
1517
1518
1519
1520
1521
1522
1523
1524
		// 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)
		}

1525
1526
1527
		models = append(models, mr)
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1528
1529
1530
1531
1532
	slices.SortStableFunc(models, func(i, j api.ProcessModelResponse) int {
		// longest duration remaining listed first
		return cmp.Compare(j.ExpiresAt.Unix(), i.ExpiresAt.Unix())
	})

1533
	c.JSON(http.StatusOK, api.ProcessResponse{Models: models})
1534
1535
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1536
func (s *Server) ChatHandler(c *gin.Context) {
1537
1538
	checkpointStart := time.Now()

Bruce MacDonald's avatar
Bruce MacDonald committed
1539
	var req api.ChatRequest
Michael Yang's avatar
Michael Yang committed
1540
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1541
1542
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
1543
	} else if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1544
1545
1546
1547
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Patrick Devine's avatar
Patrick Devine committed
1548
	// expire the runner
Michael Yang's avatar
Michael Yang committed
1549
	if len(req.Messages) == 0 && req.KeepAlive != nil && req.KeepAlive.Duration == 0 {
Patrick Devine's avatar
Patrick Devine committed
1550
1551
1552
1553
1554
		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)})
1555
			case err.Error() == errtypes.InvalidModelNameErrMsg:
Patrick Devine's avatar
Patrick Devine committed
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
				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
	}

1574
	caps := []model.Capability{model.CapabilityCompletion}
1575
	if len(req.Tools) > 0 {
1576
		caps = append(caps, model.CapabilityTools)
Michael Yang's avatar
tools  
Michael Yang committed
1577
	}
1578
	if req.Think != nil && req.Think.Bool() {
1579
1580
		caps = append(caps, model.CapabilityThinking)
	}
Michael Yang's avatar
tools  
Michael Yang committed
1581

1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
	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
1594
1595
	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
1596
		return
Michael Yang's avatar
Michael Yang committed
1597
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
1598
		handleScheduleError(c, req.Model, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
1599
1600
		return
	}
Michael Yang's avatar
Michael Yang committed
1601

1602
1603
	checkpointLoaded := time.Now()

Michael Yang's avatar
Michael Yang committed
1604
1605
	if len(req.Messages) == 0 {
		c.JSON(http.StatusOK, api.ChatResponse{
1606
			Model:      req.Model,
Michael Yang's avatar
Michael Yang committed
1607
1608
			CreatedAt:  time.Now().UTC(),
			Message:    api.Message{Role: "assistant"},
1609
1610
			Done:       true,
			DoneReason: "load",
Michael Yang's avatar
Michael Yang committed
1611
		})
1612
1613
1614
		return
	}

Michael Yang's avatar
Michael Yang committed
1615
	msgs := append(m.Messages, req.Messages...)
1616
	if req.Messages[0].Role != "system" && m.System != "" {
Michael Yang's avatar
Michael Yang committed
1617
		msgs = append([]api.Message{{Role: "system", Content: m.System}}, msgs...)
1618
	}
1619
	msgs = filterThinkTags(msgs, m)
1620

Devon Rifkin's avatar
Devon Rifkin committed
1621
	var builtinParser parsers.Parser
Devon Rifkin's avatar
Devon Rifkin committed
1622
1623
1624
1625
	if m.Config.Parser != "" {
		builtinParser = parsers.ParserForName(m.Config.Parser)
	}

1626
1627
1628
	var harmonyMessageHandler *harmony.HarmonyMessageHandler
	var harmonyToolParser *harmony.HarmonyToolCallAccumulator

Devon Rifkin's avatar
Devon Rifkin committed
1629
	useHarmony := shouldUseHarmony(m) || m.Config.Parser == "harmony"
1630
1631
1632

	processedTools := req.Tools
	if useHarmony {
1633
1634
1635
1636
1637
1638
1639
1640
		harmonyMessageHandler = harmony.NewHarmonyMessageHandler()
		var lastMessage *api.Message
		if len(msgs) > 0 {
			lastMessage = &msgs[len(msgs)-1]
		}
		harmonyMessageHandler.HarmonyParser.AddImplicitStartOrPrefill(lastMessage)
		harmonyToolParser = harmonyMessageHandler.CreateToolParser()

1641
1642
1643
1644
1645
		// make a copy of tools to pass to the chat prompt. Function names may be
		// renamed to be valid Harmony function names.
		processedTools = make([]api.Tool, len(req.Tools))
		copy(processedTools, req.Tools)
		for i, tool := range processedTools {
1646
			processedTools[i].Function.Name = harmonyMessageHandler.FunctionNameMap.ConvertAndAdd(tool.Function.Name)
1647
1648
1649
1650
		}
	}

	prompt, images, err := chatPrompt(c.Request.Context(), m, r.Tokenize, opts, msgs, processedTools, req.Think)
Michael Yang's avatar
Michael Yang committed
1651
	if err != nil {
1652
		slog.Error("chat prompt error", "error", err)
Michael Yang's avatar
Michael Yang committed
1653
1654
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
1655
1656
	}

1657
1658
	// If debug mode is enabled, return the rendered template instead of calling the model
	if req.DebugRenderOnly {
Devon Rifkin's avatar
Devon Rifkin committed
1659
		c.JSON(http.StatusOK, api.ChatResponse{
1660
1661
			Model:     req.Model,
			CreatedAt: time.Now().UTC(),
Devon Rifkin's avatar
Devon Rifkin committed
1662
			DebugInfo: &api.DebugInfo{
1663
1664
1665
1666
1667
1668
1669
				RenderedTemplate: prompt,
				ImageCount:       len(images),
			},
		})
		return
	}

Michael Yang's avatar
Michael Yang committed
1670
1671
	// Validate Think value: string values currently only allowed for gptoss models
	if req.Think != nil && req.Think.IsString() && !useHarmony {
1672
		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
1673
1674
1675
		return
	}

1676
1677
	var thinkingState *thinking.Parser
	openingTag, closingTag := thinking.InferTags(m.Template.Template)
1678
	if req.Think != nil && req.Think.Bool() && openingTag != "" && closingTag != "" {
1679
		thinkingState = &thinking.Parser{
Devon Rifkin's avatar
Devon Rifkin committed
1680
1681
			OpeningTag: openingTag,
			ClosingTag: closingTag,
1682
		}
1683
1684
1685
1686

		if strings.HasSuffix(strings.TrimSpace(prompt), openingTag) {
			thinkingState.AddContent(openingTag)
		}
1687
1688
	}

1689
	var toolParser *tools.Parser
Michael Yang's avatar
Michael Yang committed
1690
	if len(req.Tools) > 0 && !useHarmony {
1691
		toolParser = tools.NewParser(m.Template.Template, req.Tools)
1692
1693
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
1694
1695
1696
	ch := make(chan any)
	go func() {
		defer close(ch)
1697

Michael Yang's avatar
Michael Yang committed
1698
		if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
1699
1700
1701
1702
			Prompt:  prompt,
			Images:  images,
			Format:  req.Format,
			Options: opts,
Michael Yang's avatar
Michael Yang committed
1703
		}, func(r llm.CompletionResponse) {
1704
			res := api.ChatResponse{
1705
1706
				Model:     req.Model,
				CreatedAt: time.Now().UTC(),
1707
				Message:   api.Message{Role: "assistant", Content: r.Content},
1708
				Done:      r.Done,
Bruce MacDonald's avatar
Bruce MacDonald committed
1709
1710
1711
1712
1713
1714
1715
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}
Michael Yang's avatar
Michael Yang committed
1716
1717
1718
1719
1720
1721
			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
1722
			// TODO(drifkin): fold this as much as possibleinto the generic m.Config.Parser logic
Michael Yang's avatar
Michael Yang committed
1723
			if useHarmony {
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
				content, thinking, toolContent := harmonyMessageHandler.AddContent(r.Content, harmonyToolParser)
				res.Message.Content = content
				res.Message.Thinking = thinking
				harmonyToolParser.Add(toolContent)

				if r.Done {
					toolName, toolContent := harmonyToolParser.Drain()
					if toolName != nil {
						*toolName = strings.TrimPrefix(*toolName, "functions.")
						*toolName = harmonyMessageHandler.FunctionNameMap.OriginalFromConverted(*toolName)
						var args api.ToolCallFunctionArguments
						if err := json.Unmarshal([]byte(toolContent), &args); err != nil {
							errStr := fmt.Sprintf("error parsing tool call: raw='%s', err=%s", toolContent, err.Error())
							ch <- gin.H{"error": errStr}
							return
						}
						res.Message.ToolCalls = []api.ToolCall{{Function: api.ToolCallFunction{Name: *toolName, Arguments: args}}}
					}
Michael Yang's avatar
Michael Yang committed
1742
				}
1743

Michael Yang's avatar
Michael Yang committed
1744
1745
1746
1747
				// only send messages with meaningful content (empty messages confuse clients)
				if res.Message.Content != "" || res.Message.Thinking != "" || len(res.Message.ToolCalls) > 0 || res.Done {
					ch <- res
				}
1748

Devon Rifkin's avatar
Devon Rifkin committed
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
				return
			} else 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, req.Tools)
				if err != nil {
					ch <- gin.H{"error": err.Error()}
					return
				}

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

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

Michael Yang's avatar
Michael Yang committed
1770
1771
				return
			}
1772

1773
			if thinkingState != nil {
Devon Rifkin's avatar
Devon Rifkin committed
1774
				thinkingContent, remainingContent := thinkingState.AddContent(res.Message.Content)
1775
1776
1777
1778
1779
1780
1781
1782
				if thinkingContent == "" && remainingContent == "" && !r.Done {
					// need to accumulate more to decide what to send
					return
				}
				res.Message.Content = remainingContent
				res.Message.Thinking = thinkingContent
			}

1783
			if len(req.Tools) > 0 {
1784
				toolCalls, content := toolParser.Add(res.Message.Content)
1785
1786
1787
1788
1789
				if len(content) > 0 {
					res.Message.Content = content
				} else if len(toolCalls) > 0 {
					res.Message.ToolCalls = toolCalls
					res.Message.Content = ""
1790
1791
				} else if res.Message.Thinking != "" {
					// don't return
1792
1793
				} else {
					if r.Done {
1794
						res.Message.Content = toolParser.Content()
1795
1796
1797
						ch <- res
					}
					return
1798
1799
				}
			}
1800

1801
			ch <- res
Michael Yang's avatar
Michael Yang committed
1802
		}); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1803
1804
1805
1806
1807
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
Michael Yang's avatar
tools  
Michael Yang committed
1808
		var resp api.ChatResponse
1809
		var toolCalls []api.ToolCall
1810
1811
		var sbThinking strings.Builder
		var sbContent strings.Builder
Michael Yang's avatar
Michael Yang committed
1812
1813
		for rr := range ch {
			switch t := rr.(type) {
1814
			case api.ChatResponse:
1815
1816
				sbThinking.WriteString(t.Message.Thinking)
				sbContent.WriteString(t.Message.Content)
Michael Yang's avatar
tools  
Michael Yang committed
1817
				resp = t
1818
1819
1820
				if len(req.Tools) > 0 {
					toolCalls = append(toolCalls, t.Message.ToolCalls...)
				}
1821
			case gin.H:
Michael Yang's avatar
Michael Yang committed
1822
1823
1824
				msg, ok := t["error"].(string)
				if !ok {
					msg = "unexpected error format in response"
1825
				}
Michael Yang's avatar
Michael Yang committed
1826
1827
1828

				c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
				return
1829
			default:
Michael Yang's avatar
Michael Yang committed
1830
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
1831
				return
Bruce MacDonald's avatar
Bruce MacDonald committed
1832
1833
			}
		}
1834

1835
1836
1837
		resp.Message.Content = sbContent.String()
		resp.Message.Thinking = sbThinking.String()

1838
1839
		if len(toolCalls) > 0 {
			resp.Message.ToolCalls = toolCalls
Michael Yang's avatar
tools  
Michael Yang committed
1840
1841
1842
		}

		c.JSON(http.StatusOK, resp)
Bruce MacDonald's avatar
Bruce MacDonald committed
1843
1844
1845
1846
1847
		return
	}

	streamResponse(c, ch)
}
1848

Michael Yang's avatar
Michael Yang committed
1849
func handleScheduleError(c *gin.Context, name string, err error) {
Michael Yang's avatar
Michael Yang committed
1850
	switch {
1851
	case errors.Is(err, errCapabilities), errors.Is(err, errRequired):
Michael Yang's avatar
Michael Yang committed
1852
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
1853
	case errors.Is(err, context.Canceled):
1854
		c.JSON(499, gin.H{"error": "request canceled"})
Michael Yang's avatar
Michael Yang committed
1855
	case errors.Is(err, ErrMaxQueue):
1856
		c.JSON(http.StatusServiceUnavailable, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
1857
1858
	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
1859
1860
	default:
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
1861
1862
	}
}
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874

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 {
1875
1876
1877
1878
1879
				// 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.
1880
				thinkingState := &thinking.Parser{
Devon Rifkin's avatar
Devon Rifkin committed
1881
1882
					OpeningTag: "<think>",
					ClosingTag: "</think>",
1883
				}
Devon Rifkin's avatar
Devon Rifkin committed
1884
				_, content := thinkingState.AddContent(msg.Content)
1885
				msgs[i].Content = content
1886
1887
1888
1889
1890
			}
		}
	}
	return msgs
}