routes.go 56.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
	"net/url"
19
	"os"
20
	"os/signal"
21
	"slices"
Michael Yang's avatar
Michael Yang committed
22
	"strings"
23
	"syscall"
24
	"time"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
25

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

31
	"github.com/ollama/ollama/api"
32
	"github.com/ollama/ollama/auth"
33
	"github.com/ollama/ollama/discover"
34
	"github.com/ollama/ollama/envconfig"
35
	"github.com/ollama/ollama/format"
Michael Yang's avatar
Michael Yang committed
36
	"github.com/ollama/ollama/fs/ggml"
37
	"github.com/ollama/ollama/harmony"
38
	"github.com/ollama/ollama/llm"
39
	"github.com/ollama/ollama/logutil"
Devon Rifkin's avatar
Devon Rifkin committed
40
	"github.com/ollama/ollama/model/parsers"
41
	"github.com/ollama/ollama/openai"
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
54
55
56
57
58
59
60
61
62
63
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
}

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

var useClient2 = experimentEnabled("client2")

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

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

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

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

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

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

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

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

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

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

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

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

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

181
	m, err := GetModel(name.String())
182
183
	if err != nil {
		switch {
184
		case errors.Is(err, fs.ErrNotExist):
185
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
186
		case err.Error() == errtypes.InvalidModelNameErrMsg:
187
188
189
190
191
192
193
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

194
195
196
197
198
199
200
201
202
203
204
205
206
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
267
268
269
270
271
	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 {
			var sErr api.AuthorizationError
			if errors.As(err, &sErr) && sErr.StatusCode == http.StatusUnauthorized {
				pk, pkErr := auth.GetPublicKey()
				if pkErr != nil {
					slog.Error("couldn't get public key", "error", pkErr)
					c.JSON(http.StatusUnauthorized, gin.H{"error": "error getting public key"})
					return
				}
				c.JSON(http.StatusUnauthorized, gin.H{"public_key": pk})
				return
			}
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		return
	}

Patrick Devine's avatar
Patrick Devine committed
272
	// expire the runner
Michael Yang's avatar
Michael Yang committed
273
	if req.Prompt == "" && req.KeepAlive != nil && req.KeepAlive.Duration == 0 {
274
		s.sched.expireRunner(m)
Patrick Devine's avatar
Patrick Devine committed
275
276
277
278
279
280
281
282
283
284
285

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

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

291
292
293
	useHarmony := shouldUseHarmony(m) && !req.Raw
	var harmonyMessageHandler *harmony.HarmonyMessageHandler
	var harmonyToolParser *harmony.HarmonyToolCallAccumulator
Michael Yang's avatar
Michael Yang committed
294
	if useHarmony {
295
296
297
		harmonyMessageHandler = harmony.NewHarmonyMessageHandler()
		harmonyMessageHandler.HarmonyParser.AddImplicitStart()
		harmonyToolParser = harmonyMessageHandler.CreateToolParser()
Michael Yang's avatar
Michael Yang committed
298
299
300
301
	}

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

306
	caps := []model.Capability{model.CapabilityCompletion}
307
	if req.Suffix != "" {
308
		caps = append(caps, model.CapabilityInsert)
309
	}
310
	if req.Think != nil && req.Think.Bool() {
311
312
313
314
315
316
		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
	}
317

318
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), caps, req.Options, req.KeepAlive)
Michael Yang's avatar
Michael Yang committed
319
320
321
322
	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
323
324
325
326
		handleScheduleError(c, req.Model, err)
		return
	}

327
328
	checkpointLoaded := time.Now()

329
	// load the model
Michael Yang's avatar
Michael Yang committed
330
331
332
333
334
335
336
	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
337
338
		return
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
339

340
341
	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"})
342
343
344
		return
	}

Michael Yang's avatar
Michael Yang committed
345
346
	images := make([]llm.ImageData, len(req.Images))
	for i := range req.Images {
347
		images[i] = llm.ImageData{ID: i, Data: req.Images[i]}
Michael Yang's avatar
Michael Yang committed
348
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
349

Michael Yang's avatar
Michael Yang committed
350
351
	prompt := req.Prompt
	if !req.Raw {
Michael Yang's avatar
Michael Yang committed
352
		tmpl := m.Template
Michael Yang's avatar
Michael Yang committed
353
354
355
356
357
358
359
360
		if req.Template != "" {
			tmpl, err = template.Parse(req.Template)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}

361
362
363
364
365
366
367
368
369
370
371
372
		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
373
374
375
376
			if req.Context == nil {
				msgs = append(msgs, m.Messages...)
			}

377
			for _, i := range images {
378
379
				imgPrompt := ""
				msgs = append(msgs, api.Message{Role: "user", Content: fmt.Sprintf("[img-%d]"+imgPrompt, i.ID)})
380
381
382
383
384
			}

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

385
		values.Think = req.Think != nil && req.Think.Bool()
Michael Yang's avatar
Michael Yang committed
386
387
		values.ThinkLevel = ""
		if req.Think != nil {
388
			values.ThinkLevel = req.Think.String()
Michael Yang's avatar
Michael Yang committed
389
		}
390
391
		values.IsThinkSet = req.Think != nil

Michael Yang's avatar
Michael Yang committed
392
393
		var b bytes.Buffer
		if req.Context != nil {
394
			slog.Warn("the context field is deprecated and will be removed in a future version of Ollama")
395
			s, err := r.Detokenize(c.Request.Context(), req.Context)
Michael Yang's avatar
Michael Yang committed
396
397
398
399
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
400
			b.WriteString(s)
Michael Yang's avatar
Michael Yang committed
401
		}
402
403
404
405
406
407
408

		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
409
410
	}

411
412
	// If debug mode is enabled, return the rendered template instead of calling the model
	if req.DebugRenderOnly {
Devon Rifkin's avatar
Devon Rifkin committed
413
		c.JSON(http.StatusOK, api.GenerateResponse{
414
415
			Model:     req.Model,
			CreatedAt: time.Now().UTC(),
Devon Rifkin's avatar
Devon Rifkin committed
416
			DebugInfo: &api.DebugInfo{
417
418
419
420
421
422
423
				RenderedTemplate: prompt,
				ImageCount:       len(images),
			},
		})
		return
	}

424
	var thinkingState *thinking.Parser
Michael Yang's avatar
Michael Yang committed
425
426
	if !useHarmony {
		openingTag, closingTag := thinking.InferTags(m.Template.Template)
427
		if req.Think != nil && req.Think.Bool() && openingTag != "" && closingTag != "" {
Michael Yang's avatar
Michael Yang committed
428
429
430
431
			thinkingState = &thinking.Parser{
				OpeningTag: openingTag,
				ClosingTag: closingTag,
			}
432
433
434
		}
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
435
436
	ch := make(chan any)
	go func() {
437
438
		// TODO (jmorganca): avoid building the response twice both here and below
		var sb strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
439
		defer close(ch)
Michael Yang's avatar
Michael Yang committed
440
		if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
441
442
443
444
			Prompt:  prompt,
			Images:  images,
			Format:  req.Format,
			Options: opts,
445
446
		}, func(cr llm.CompletionResponse) {
			res := api.GenerateResponse{
447
448
449
450
				Model:     req.Model,
				CreatedAt: time.Now().UTC(),
				Response:  cr.Content,
				Done:      cr.Done,
Bruce MacDonald's avatar
Bruce MacDonald committed
451
				Metrics: api.Metrics{
452
453
454
455
					PromptEvalCount:    cr.PromptEvalCount,
					PromptEvalDuration: cr.PromptEvalDuration,
					EvalCount:          cr.EvalCount,
					EvalDuration:       cr.EvalDuration,
Bruce MacDonald's avatar
Bruce MacDonald committed
456
				},
Bruce MacDonald's avatar
Bruce MacDonald committed
457
			}
458

Michael Yang's avatar
Michael Yang committed
459
			if useHarmony {
460
461
462
463
464
				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
465
				thinking, content := thinkingState.AddContent(cr.Content)
466
467
468
469
				res.Thinking = thinking
				res.Response = content
			}

470
471
472
473
474
			if _, err := sb.WriteString(cr.Content); err != nil {
				ch <- gin.H{"error": err.Error()}
			}

			if cr.Done {
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
				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)

499
				if !req.Raw {
500
					tokens, err := r.Tokenize(c.Request.Context(), prompt+sb.String())
501
502
503
504
					if err != nil {
						ch <- gin.H{"error": err.Error()}
						return
					}
505
					res.Context = tokens
506
507
508
				}
			}

Michael Yang's avatar
Michael Yang committed
509
510
511
512
513
514
515
516
517
			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
			}

518
			ch <- res
Michael Yang's avatar
Michael Yang committed
519
		}); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
520
521
522
523
524
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
Michael Yang's avatar
Michael Yang committed
525
		var r api.GenerateResponse
526
527
		var sbThinking strings.Builder
		var sbContent strings.Builder
Michael Yang's avatar
Michael Yang committed
528
529
		for rr := range ch {
			switch t := rr.(type) {
530
			case api.GenerateResponse:
531
532
				sbThinking.WriteString(t.Thinking)
				sbContent.WriteString(t.Response)
Michael Yang's avatar
Michael Yang committed
533
				r = t
534
			case gin.H:
Michael Yang's avatar
Michael Yang committed
535
536
537
				msg, ok := t["error"].(string)
				if !ok {
					msg = "unexpected error format in response"
538
				}
Michael Yang's avatar
Michael Yang committed
539
540
541

				c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
				return
542
			default:
Michael Yang's avatar
Michael Yang committed
543
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
Bruce MacDonald's avatar
Bruce MacDonald committed
544
545
546
				return
			}
		}
547

548
549
550
		r.Thinking = sbThinking.String()
		r.Response = sbContent.String()

Michael Yang's avatar
Michael Yang committed
551
		c.JSON(http.StatusOK, r)
Bruce MacDonald's avatar
Bruce MacDonald committed
552
553
554
555
556
557
		return
	}

	streamResponse(c, ch)
}

558
func (s *Server) EmbedHandler(c *gin.Context) {
559
	checkpointStart := time.Now()
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
	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:
592
593
594
595
		if req.Input != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid input type"})
			return
		}
596
597
	}

598
599
600
601
602
603
	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
	}

604
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), []model.Capability{}, req.Options, req.KeepAlive)
605
606
607
608
609
	if err != nil {
		handleScheduleError(c, req.Model, err)
		return
	}

610
611
	checkpointLoaded := time.Now()

612
613
614
615
616
	if len(input) == 0 {
		c.JSON(http.StatusOK, api.EmbedResponse{Model: req.Model, Embeddings: [][]float32{}})
		return
	}

617
	kvData, _, err := getModelData(m.ModelPath, false)
618
619
620
621
622
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

623
	var count int
624
625
626
627
628
629
630
631
632
633
634
635
636
637
	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
			}

638
639
640
641
642
643
644
645
			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--
			}

646
			tokens = tokens[:ctxLen]
647

648
649
650
651
652
653
654
			s, err = r.Detokenize(c.Request.Context(), tokens)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}

655
656
		count += len(tokens)

657
658
		input[i] = s
	}
659
660
661
662
663
664
665
666
667

	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
			}
668
669
670
671
672
673
			// 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
674
675
			return nil
		})
676
677
	}

678
	if err := g.Wait(); err != nil {
679
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": strings.TrimSpace(err.Error())})
680
		return
681
682
683
	}

	resp := api.EmbedResponse{
684
		Model:           req.Model,
685
		Embeddings:      embeddings,
686
687
		TotalDuration:   time.Since(checkpointStart),
		LoadDuration:    checkpointLoaded.Sub(checkpointStart),
688
		PromptEvalCount: count,
689
690
691
692
693
694
695
696
697
698
	}
	c.JSON(http.StatusOK, resp)
}

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

699
	norm := float32(1.0 / max(math.Sqrt(float64(sum)), 1e-12))
700
701
702
703
704
705
	for i := range vec {
		vec[i] *= norm
	}
	return vec
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
706
func (s *Server) EmbeddingsHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
707
	var req api.EmbeddingRequest
Michael Yang's avatar
Michael Yang committed
708
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
Bruce MacDonald's avatar
Bruce MacDonald committed
709
710
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
711
	} else if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
712
713
714
715
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

716
717
718
719
720
721
	name := model.ParseName(req.Model)
	if !name.IsValid() {
		c.JSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
	}

722
	r, _, _, err := s.scheduleRunner(c.Request.Context(), name.String(), []model.Capability{}, req.Options, req.KeepAlive)
Bruce MacDonald's avatar
Bruce MacDonald committed
723
	if err != nil {
Michael Yang's avatar
Michael Yang committed
724
		handleScheduleError(c, req.Model, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
725
726
727
		return
	}

728
729
730
	// an empty request loads the model
	if req.Prompt == "" {
		c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: []float64{}})
Bruce MacDonald's avatar
Bruce MacDonald committed
731
732
733
		return
	}

734
	embedding, err := r.Embedding(c.Request.Context(), req.Prompt)
Bruce MacDonald's avatar
Bruce MacDonald committed
735
	if err != nil {
736
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": strings.TrimSpace(err.Error())})
Bruce MacDonald's avatar
Bruce MacDonald committed
737
738
739
		return
	}

740
741
742
	var e []float64
	for _, v := range embedding {
		e = append(e, float64(v))
743
744
745
	}

	resp := api.EmbeddingResponse{
746
		Embedding: e,
747
748
	}
	c.JSON(http.StatusOK, resp)
Bruce MacDonald's avatar
Bruce MacDonald committed
749
750
}

751
func (s *Server) PullHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
752
	var req api.PullRequest
Michael Yang's avatar
Michael Yang committed
753
754
755
756
757
758
759
	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
760
761
762
		return
	}

763
764
	name := model.ParseName(cmp.Or(req.Model, req.Name))
	if !name.IsValid() {
765
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": errtypes.InvalidModelNameErrMsg})
766
767
768
		return
	}

769
770
	name, err = getExistingName(name)
	if err != nil {
771
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
772
773
774
		return
	}

775
776
777
	ch := make(chan any)
	go func() {
		defer close(ch)
778
779
		fn := func(r api.ProgressResponse) {
			ch <- r
780
		}
781

Michael Yang's avatar
Michael Yang committed
782
		regOpts := &registryOptions{
783
784
785
			Insecure: req.Insecure,
		}

786
787
788
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

789
		if err := PullModel(ctx, name.DisplayShortest(), regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
790
			ch <- gin.H{"error": err.Error()}
791
792
793
		}
	}()

794
795
796
797
798
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

799
800
801
	streamResponse(c, ch)
}

802
func (s *Server) PushHandler(c *gin.Context) {
803
	var req api.PushRequest
Michael Yang's avatar
Michael Yang committed
804
805
806
807
808
809
810
	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
811
812
		return
	}
Michael Yang's avatar
Michael Yang committed
813

814
	var mname string
Michael Yang's avatar
Michael Yang committed
815
	if req.Model != "" {
816
		mname = req.Model
Michael Yang's avatar
Michael Yang committed
817
	} else if req.Name != "" {
818
		mname = req.Name
Michael Yang's avatar
Michael Yang committed
819
820
	} else {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
821
822
823
		return
	}

824
825
826
	ch := make(chan any)
	go func() {
		defer close(ch)
827
828
		fn := func(r api.ProgressResponse) {
			ch <- r
829
		}
830

Michael Yang's avatar
Michael Yang committed
831
		regOpts := &registryOptions{
832
833
834
			Insecure: req.Insecure,
		}

Michael Yang's avatar
Michael Yang committed
835
836
837
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

838
839
840
841
842
843
844
		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
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
858
859
860
// 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.
861
862
863
func getExistingName(n model.Name) (model.Name, error) {
	var zero model.Name
	existing, err := Manifests(true)
864
	if err != nil {
865
		return zero, err
866
	}
867
	var set model.Name // tracks parts already canonicalized
868
	for e := range existing {
869
870
871
872
873
874
875
876
877
878
879
		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
880
881
		}
	}
882
	return n, nil
883
884
}

885
func (s *Server) DeleteHandler(c *gin.Context) {
886
887
	var r api.DeleteRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
888
889
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
890
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
891
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
892
893
894
		return
	}

895
896
897
	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))})
898
899
		return
	}
Michael Yang's avatar
Michael Yang committed
900

901
902
903
904
905
906
	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
	}

907
	m, err := ParseNamedManifest(n)
Michael Yang's avatar
Michael Yang committed
908
	if err != nil {
909
910
911
912
913
914
		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
915
916
917
		return
	}

918
	if err := m.Remove(); err != nil {
Michael Yang's avatar
Michael Yang committed
919
920
921
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
922
923
924
925
926

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

929
func (s *Server) ShowHandler(c *gin.Context) {
Patrick Devine's avatar
Patrick Devine committed
930
	var req api.ShowRequest
Michael Yang's avatar
Michael Yang committed
931
932
933
934
935
936
937
	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
938
939
940
		return
	}

Michael Yang's avatar
Michael Yang committed
941
	if req.Model != "" {
Michael Yang's avatar
Michael Yang committed
942
		// noop
Michael Yang's avatar
Michael Yang committed
943
	} else if req.Name != "" {
Michael Yang's avatar
Michael Yang committed
944
		req.Model = req.Name
Michael Yang's avatar
Michael Yang committed
945
	} else {
946
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
947
948
949
		return
	}

950
	resp, err := GetModelInfo(req)
Patrick Devine's avatar
Patrick Devine committed
951
	if err != nil {
952
953
		switch {
		case os.IsNotExist(err):
Michael Yang's avatar
Michael Yang committed
954
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
955
		case err.Error() == errtypes.InvalidModelNameErrMsg:
956
957
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
Patrick Devine's avatar
Patrick Devine committed
958
959
960
961
962
963
964
965
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

	c.JSON(http.StatusOK, resp)
}

966
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
967
968
	name := model.ParseName(req.Model)
	if !name.IsValid() {
CYJiang's avatar
CYJiang committed
969
		return nil, ErrModelPathInvalid
970
971
972
973
974
975
976
	}
	name, err := getExistingName(name)
	if err != nil {
		return nil, err
	}

	m, err := GetModel(name.String())
Patrick Devine's avatar
Patrick Devine committed
977
978
979
980
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
981
	modelDetails := api.ModelDetails{
982
983
984
985
986
987
		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
988
989
	}

990
	if req.System != "" {
991
		m.System = req.System
992
993
	}

Michael Yang's avatar
Michael Yang committed
994
995
996
	msgs := make([]api.Message, len(m.Messages))
	for i, msg := range m.Messages {
		msgs[i] = api.Message{Role: msg.Role, Content: msg.Content}
997
998
	}

999
	manifest, err := ParseNamedManifest(name)
1000
1001
1002
1003
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
1004
	resp := &api.ShowResponse{
1005
1006
1007
1008
1009
1010
1011
		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
1012
1013
	}

1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
	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
1036
1037
	var params []string
	cs := 30
1038
	for k, v := range m.Options {
Patrick Devine's avatar
Patrick Devine committed
1039
		switch val := v.(type) {
1040
		case []any:
Patrick Devine's avatar
Patrick Devine committed
1041
			for _, nv := range val {
Patrick Devine's avatar
Patrick Devine committed
1042
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
Patrick Devine's avatar
Patrick Devine committed
1043
			}
Patrick Devine's avatar
Patrick Devine committed
1044
1045
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
Patrick Devine's avatar
Patrick Devine committed
1046
1047
1048
1049
		}
	}
	resp.Parameters = strings.Join(params, "\n")

Patrick Devine's avatar
Patrick Devine committed
1050
1051
1052
1053
1054
	if len(req.Options) > 0 {
		if m.Options == nil {
			m.Options = make(map[string]any)
		}
		for k, v := range req.Options {
1055
			m.Options[k] = v
1056
1057
1058
		}
	}

1059
	var sb strings.Builder
1060
	fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"")
1061
	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
1062
1063
	fmt.Fprintf(&sb, "# FROM %s\n\n", m.ShortName)
	fmt.Fprint(&sb, m.String())
1064
	resp.Modelfile = sb.String()
1065

1066
1067
1068
1069
1070
	// skip loading tensor information if this is a remote model
	if m.Config.RemoteHost != "" && m.Config.RemoteModel != "" {
		return resp, nil
	}

1071
	kvData, tensors, err := getModelData(m.ModelPath, req.Verbose)
1072
1073
1074
	if err != nil {
		return nil, err
	}
1075

1076
1077
1078
1079
	delete(kvData, "general.name")
	delete(kvData, "tokenizer.chat_template")
	resp.ModelInfo = kvData

1080
1081
1082
1083
1084
1085
	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

1086
	if len(m.ProjectorPaths) > 0 {
1087
		projectorData, _, err := getModelData(m.ProjectorPaths[0], req.Verbose)
1088
1089
1090
1091
1092
1093
		if err != nil {
			return nil, err
		}
		resp.ProjectorInfo = projectorData
	}

Patrick Devine's avatar
Patrick Devine committed
1094
1095
1096
	return resp, nil
}

1097
func getModelData(digest string, verbose bool) (ggml.KV, ggml.Tensors, error) {
1098
1099
1100
1101
	maxArraySize := 0
	if verbose {
		maxArraySize = -1
	}
1102
	data, err := llm.LoadModel(digest, maxArraySize)
1103
	if err != nil {
1104
		return nil, ggml.Tensors{}, err
1105
1106
	}

1107
	kv := data.KV()
1108
1109
1110
1111
1112
1113
1114
1115
1116

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

1117
	return kv, data.Tensors(), nil
1118
1119
}

1120
func (s *Server) ListHandler(c *gin.Context) {
1121
	ms, err := Manifests(true)
Patrick Devine's avatar
Patrick Devine committed
1122
1123
1124
1125
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
1126

1127
	models := []api.ListModelResponse{}
1128
1129
	for n, m := range ms {
		var cf ConfigV2
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142

		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
1143
		}
Michael Yang's avatar
Michael Yang committed
1144

1145
1146
		// tag should never be masked
		models = append(models, api.ListModelResponse{
1147
1148
1149
1150
1151
1152
1153
			Model:       n.DisplayShortest(),
			Name:        n.DisplayShortest(),
			RemoteModel: cf.RemoteModel,
			RemoteHost:  cf.RemoteHost,
			Size:        m.Size(),
			Digest:      m.digest,
			ModifiedAt:  m.fi.ModTime(),
1154
1155
1156
1157
1158
1159
1160
			Details: api.ModelDetails{
				Format:            cf.ModelFormat,
				Family:            cf.ModelFamily,
				Families:          cf.ModelFamilies,
				ParameterSize:     cf.ModelType,
				QuantizationLevel: cf.FileType,
			},
1161
		})
Patrick Devine's avatar
Patrick Devine committed
1162
1163
	}

1164
	slices.SortStableFunc(models, func(i, j api.ListModelResponse) int {
1165
1166
1167
1168
		// most recently modified first
		return cmp.Compare(j.ModifiedAt.Unix(), i.ModifiedAt.Unix())
	})

Michael Yang's avatar
Michael Yang committed
1169
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
1170
1171
}

1172
func (s *Server) CopyHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1173
1174
	var r api.CopyRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
1175
1176
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
1177
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
1178
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Patrick Devine's avatar
Patrick Devine committed
1179
1180
1181
		return
	}

Michael Yang's avatar
Michael Yang committed
1182
1183
	src := model.ParseName(r.Source)
	if !src.IsValid() {
Michael Yang's avatar
Michael Yang committed
1184
1185
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("source %q is invalid", r.Source)})
		return
1186
	}
1187
1188
1189
1190
1191
	src, err := getExistingName(src)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
1192

Michael Yang's avatar
Michael Yang committed
1193
1194
	dst := model.ParseName(r.Destination)
	if !dst.IsValid() {
1195
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("destination %q is invalid", r.Destination)})
Patrick Devine's avatar
Patrick Devine committed
1196
1197
		return
	}
1198
1199
	dst, err = getExistingName(dst)
	if err != nil {
1200
1201
1202
1203
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
1204
1205
1206
1207
1208
	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
1209
1210
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1211
func (s *Server) HeadBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
	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
1223
	c.Status(http.StatusOK)
Michael Yang's avatar
Michael Yang committed
1224
1225
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1226
func (s *Server) CreateBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1227
1228
	if ib, ok := intermediateBlobs[c.Param("digest")]; ok {
		p, err := GetBlobsPath(ib)
1229
1230
1231
1232
1233
1234
		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
1235
1236
			slog.Info("evicting intermediate blob which no longer exists", "digest", ib)
			delete(intermediateBlobs, c.Param("digest"))
1237
1238
1239
1240
1241
1242
1243
1244
1245
		} else if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		} else {
			c.Status(http.StatusOK)
			return
		}
	}

1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
	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
	}

1264
	layer, err := NewLayer(c.Request.Body, "")
Michael Yang's avatar
Michael Yang committed
1265
1266
1267
1268
1269
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

1270
1271
	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
1272
1273
1274
		return
	}

Michael Yang's avatar
Michael Yang committed
1275
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
1276
1277
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
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
}

1299
func allowedHost(host string) bool {
1300
1301
	host = strings.ToLower(host)

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1302
	if host == "" || host == "localhost" {
1303
1304
1305
		return true
	}

1306
	if hostname, err := os.Hostname(); err == nil && host == strings.ToLower(hostname) {
1307
1308
1309
		return true
	}

Michael Yang's avatar
lint  
Michael Yang committed
1310
	tlds := []string{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1311
1312
1313
		"localhost",
		"local",
		"internal",
1314
	}
1315

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1316
	// check if the host is a local TLD
1317
1318
1319
1320
1321
1322
	for _, tld := range tlds {
		if strings.HasSuffix(host, "."+tld) {
			return true
		}
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1323
	return false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1324
}
1325

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1326
1327
1328
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
	return func(c *gin.Context) {
		if addr == nil {
1329
1330
1331
1332
			c.Next()
			return
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1333
		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
1334
1335
1336
1337
1338
1339
1340
1341
1342
			c.Next()
			return
		}

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1343
		if addr, err := netip.ParseAddr(host); err == nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1344
			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1345
1346
1347
1348
1349
				c.Next()
				return
			}
		}

1350
		if allowedHost(host) {
Michael Yang's avatar
lint  
Michael Yang committed
1351
			if c.Request.Method == http.MethodOptions {
1352
1353
1354
1355
				c.AbortWithStatus(http.StatusNoContent)
				return
			}

1356
1357
1358
1359
1360
1361
			c.Next()
			return
		}

		c.AbortWithStatus(http.StatusForbidden)
	}
1362
}
1363

1364
func (s *Server) GenerateRoutes(rc *ollama.Registry) (http.Handler, error) {
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
	corsConfig := cors.DefaultConfig()
	corsConfig.AllowWildcard = true
	corsConfig.AllowBrowserExtensions = true
	corsConfig.AllowHeaders = []string{
		"Authorization",
		"Content-Type",
		"User-Agent",
		"Accept",
		"X-Requested-With",

		// OpenAI compatibility headers
1376
1377
1378
1379
1380
		"OpenAI-Beta",
		"x-stainless-arch",
		"x-stainless-async",
		"x-stainless-custom-poll-interval",
		"x-stainless-helper-method",
1381
1382
		"x-stainless-lang",
		"x-stainless-os",
1383
1384
		"x-stainless-package-version",
		"x-stainless-poll-helper",
1385
1386
1387
1388
1389
1390
		"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
1391

Bruce MacDonald's avatar
Bruce MacDonald committed
1392
	r := gin.Default()
1393
	r.HandleMethodNotAllowed = true
1394
	r.Use(
1395
		cors.New(corsConfig),
1396
		allowedHostsMiddleware(s.addr),
1397
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
1398

1399
1400
1401
1402
1403
1404
	// 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}) })

1405
	// Local model cache management (new implementation is at end of function)
1406
1407
	r.POST("/api/pull", s.PullHandler)
	r.POST("/api/push", s.PushHandler)
1408
1409
	r.HEAD("/api/tags", s.ListHandler)
	r.GET("/api/tags", s.ListHandler)
1410
	r.POST("/api/show", s.ShowHandler)
1411
	r.DELETE("/api/delete", s.DeleteHandler)
1412

1413
1414
1415
	r.DELETE("/api/user/keys/:encodedKey", s.SignoutHandler)
	r.POST("/api/me", s.WhoamiHandler)

1416
1417
	// Create
	r.POST("/api/create", s.CreateHandler)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1418
1419
	r.POST("/api/blobs/:digest", s.CreateBlobHandler)
	r.HEAD("/api/blobs/:digest", s.HeadBlobHandler)
1420
1421
1422
	r.POST("/api/copy", s.CopyHandler)

	// Inference
1423
	r.GET("/api/ps", s.PsHandler)
1424
1425
1426
1427
	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
1428

1429
	// Inference (OpenAI compatibility)
1430
	r.POST("/v1/chat/completions", openai.ChatMiddleware(), s.ChatHandler)
1431
	r.POST("/v1/completions", openai.CompletionsMiddleware(), s.GenerateHandler)
1432
	r.POST("/v1/embeddings", openai.EmbeddingsMiddleware(), s.EmbedHandler)
1433
1434
	r.GET("/v1/models", openai.ListMiddleware(), s.ListHandler)
	r.GET("/v1/models/:model", openai.RetrieveMiddleware(), s.ShowHandler)
1435

1436
1437
1438
1439
1440
1441
	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,
1442

1443
1444
1445
			Prune: PruneLayers,
		}
		return rs, nil
1446
1447
	}

1448
	return r, nil
1449
1450
1451
}

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

1455
1456
1457
1458
1459
1460
1461
1462
	blobsDir, err := GetBlobsPath("")
	if err != nil {
		return err
	}
	if err := fixBlobs(blobsDir); err != nil {
		return err
	}

Michael Yang's avatar
bool  
Michael Yang committed
1463
	if !envconfig.NoPrune() {
1464
1465
1466
1467
1468
1469
1470
		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
			}
1471

1472
1473
1474
1475
			manifestsPath, err := GetManifestPath()
			if err != nil {
				return err
			}
1476

1477
1478
1479
			if err := PruneDirectory(manifestsPath); err != nil {
				return err
			}
1480
1481
1482
		}
	}

1483
1484
	s := &Server{addr: ln.Addr()}

1485
1486
1487
1488
1489
1490
1491
	var rc *ollama.Registry
	if useClient2 {
		var err error
		rc, err = ollama.DefaultRegistry()
		if err != nil {
			return err
		}
1492
1493
	}

1494
	h, err := s.GenerateRoutes(rc)
1495
1496
1497
	if err != nil {
		return err
	}
1498

1499
1500
	http.Handle("/", h)

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1501
	ctx, done := context.WithCancel(context.Background())
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1502
1503
	schedCtx, schedDone := context.WithCancel(ctx)
	sched := InitScheduler(schedCtx)
1504
	s.sched = sched
1505

1506
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1507
	srvr := &http.Server{
1508
1509
1510
1511
1512
1513
1514
1515
1516
		// 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
1517
1518
	}

1519
1520
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
1521
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
1522
1523
	go func() {
		<-signals
1524
		srvr.Close()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1525
		schedDone()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1526
		sched.unloadAllRunners()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1527
		done()
1528
1529
	}()

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1530
	s.sched.Run(schedCtx)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1531

1532
1533
1534
1535
	// 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
1536
1537
	// 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
1538
	gpus := discover.GetGPUInfo()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1539
	gpus.LogDetails()
1540

1541
1542
1543
1544
1545
1546
1547
1548
1549
	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
1550
1551
1552
1553
1554
1555
1556
	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()
1557
	return nil
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1558
}
Michael Yang's avatar
Michael Yang committed
1559

1560
func waitForStream(c *gin.Context, ch chan any) {
1561
	c.Header("Content-Type", "application/json")
1562
	var latest api.ProgressResponse
1563
1564
1565
	for resp := range ch {
		switch r := resp.(type) {
		case api.ProgressResponse:
1566
			latest = r
1567
		case gin.H:
Josh's avatar
Josh committed
1568
1569
1570
1571
			status, ok := r["status"].(int)
			if !ok {
				status = http.StatusInternalServerError
			}
1572
1573
1574
			errorMsg, ok := r["error"].(string)
			if !ok {
				errorMsg = "unknown error"
1575
			}
1576
1577
			c.JSON(status, gin.H{"error": errorMsg})
			return
1578
		default:
1579
			c.JSON(http.StatusInternalServerError, gin.H{"error": "unknown message type"})
1580
1581
1582
			return
		}
	}
1583
1584

	c.JSON(http.StatusOK, latest)
1585
1586
}

Michael Yang's avatar
Michael Yang committed
1587
func streamResponse(c *gin.Context, ch chan any) {
1588
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
1589
1590
1591
1592
1593
1594
1595
1596
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

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

1601
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
1602
1603
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
1604
			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1605
1606
1607
1608
1609
1610
			return false
		}

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

1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
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())
	}
	c.JSON(http.StatusOK, user)
}

func (s *Server) SignoutHandler(c *gin.Context) {
	encodedKey := c.Param("encodedKey")

	// 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)
	err = client.Signout(c, encodedKey)
	if err != nil {
		slog.Error(err.Error())
		if strings.Contains(err.Error(), "page not found") || strings.Contains(err.Error(), "invalid credentials") {
			c.JSON(http.StatusNotFound, gin.H{"error": "you are not currently signed in"})
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": "there was an error signing out"})
		return
	}

	c.JSON(http.StatusOK, nil)
}

1655
func (s *Server) PsHandler(c *gin.Context) {
1656
	models := []api.ProcessModelResponse{}
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667

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

1668
		mr := api.ProcessModelResponse{
1669
1670
			Model:     model.ShortName,
			Name:      model.ShortName,
Jesse Gross's avatar
Jesse Gross committed
1671
1672
			Size:      int64(v.totalSize),
			SizeVRAM:  int64(v.vramSize),
1673
1674
1675
1676
			Digest:    model.Digest,
			Details:   modelDetails,
			ExpiresAt: v.expiresAt,
		}
1677
		if v.Options != nil {
Jesse Gross's avatar
Jesse Gross committed
1678
			mr.ContextLength = v.Options.NumCtx
1679
		}
1680
1681
1682
1683
1684
1685
1686
1687
		// 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)
		}

1688
1689
1690
		models = append(models, mr)
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1691
1692
1693
1694
1695
	slices.SortStableFunc(models, func(i, j api.ProcessModelResponse) int {
		// longest duration remaining listed first
		return cmp.Compare(j.ExpiresAt.Unix(), i.ExpiresAt.Unix())
	})

1696
	c.JSON(http.StatusOK, api.ProcessResponse{Models: models})
1697
1698
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1699
func (s *Server) ChatHandler(c *gin.Context) {
1700
1701
	checkpointStart := time.Now()

Bruce MacDonald's avatar
Bruce MacDonald committed
1702
	var req api.ChatRequest
Michael Yang's avatar
Michael Yang committed
1703
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1704
1705
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
1706
	} else if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1707
1708
1709
1710
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
	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
1732
		}
1733
1734
1735
1736
1737
1738
		return
	}

	// expire the runner
	if len(req.Messages) == 0 && req.KeepAlive != nil && int(req.KeepAlive.Seconds()) == 0 {
		s.sched.expireRunner(m)
Patrick Devine's avatar
Patrick Devine committed
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749

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

1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
	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 {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		return
	}

1810
	caps := []model.Capability{model.CapabilityCompletion}
1811
	if len(req.Tools) > 0 {
1812
		caps = append(caps, model.CapabilityTools)
Michael Yang's avatar
tools  
Michael Yang committed
1813
	}
1814
	if req.Think != nil && req.Think.Bool() {
1815
1816
		caps = append(caps, model.CapabilityThinking)
	}
Michael Yang's avatar
tools  
Michael Yang committed
1817

1818
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), caps, req.Options, req.KeepAlive)
Michael Yang's avatar
Michael Yang committed
1819
1820
	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
1821
		return
Michael Yang's avatar
Michael Yang committed
1822
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
1823
		handleScheduleError(c, req.Model, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
1824
1825
		return
	}
Michael Yang's avatar
Michael Yang committed
1826

1827
1828
	checkpointLoaded := time.Now()

Michael Yang's avatar
Michael Yang committed
1829
1830
	if len(req.Messages) == 0 {
		c.JSON(http.StatusOK, api.ChatResponse{
1831
			Model:      req.Model,
Michael Yang's avatar
Michael Yang committed
1832
1833
			CreatedAt:  time.Now().UTC(),
			Message:    api.Message{Role: "assistant"},
1834
1835
			Done:       true,
			DoneReason: "load",
Michael Yang's avatar
Michael Yang committed
1836
		})
1837
1838
1839
		return
	}

Michael Yang's avatar
Michael Yang committed
1840
	msgs := append(m.Messages, req.Messages...)
1841
	if req.Messages[0].Role != "system" && m.System != "" {
Michael Yang's avatar
Michael Yang committed
1842
		msgs = append([]api.Message{{Role: "system", Content: m.System}}, msgs...)
1843
	}
1844
	msgs = filterThinkTags(msgs, m)
1845

Devon Rifkin's avatar
Devon Rifkin committed
1846
	var builtinParser parsers.Parser
Devon Rifkin's avatar
Devon Rifkin committed
1847
1848
1849
1850
	if m.Config.Parser != "" {
		builtinParser = parsers.ParserForName(m.Config.Parser)
	}

1851
1852
1853
	var harmonyMessageHandler *harmony.HarmonyMessageHandler
	var harmonyToolParser *harmony.HarmonyToolCallAccumulator

Devon Rifkin's avatar
Devon Rifkin committed
1854
	useHarmony := shouldUseHarmony(m) || m.Config.Parser == "harmony"
1855
1856
1857

	processedTools := req.Tools
	if useHarmony {
1858
1859
1860
1861
1862
1863
1864
1865
		harmonyMessageHandler = harmony.NewHarmonyMessageHandler()
		var lastMessage *api.Message
		if len(msgs) > 0 {
			lastMessage = &msgs[len(msgs)-1]
		}
		harmonyMessageHandler.HarmonyParser.AddImplicitStartOrPrefill(lastMessage)
		harmonyToolParser = harmonyMessageHandler.CreateToolParser()

1866
1867
1868
1869
1870
		// 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 {
1871
			processedTools[i].Function.Name = harmonyMessageHandler.FunctionNameMap.ConvertAndAdd(tool.Function.Name)
1872
1873
1874
1875
		}
	}

	prompt, images, err := chatPrompt(c.Request.Context(), m, r.Tokenize, opts, msgs, processedTools, req.Think)
Michael Yang's avatar
Michael Yang committed
1876
	if err != nil {
1877
		slog.Error("chat prompt error", "error", err)
Michael Yang's avatar
Michael Yang committed
1878
1879
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
1880
1881
	}

1882
1883
	// If debug mode is enabled, return the rendered template instead of calling the model
	if req.DebugRenderOnly {
Devon Rifkin's avatar
Devon Rifkin committed
1884
		c.JSON(http.StatusOK, api.ChatResponse{
1885
1886
			Model:     req.Model,
			CreatedAt: time.Now().UTC(),
Devon Rifkin's avatar
Devon Rifkin committed
1887
			DebugInfo: &api.DebugInfo{
1888
1889
1890
1891
1892
1893
1894
				RenderedTemplate: prompt,
				ImageCount:       len(images),
			},
		})
		return
	}

Michael Yang's avatar
Michael Yang committed
1895
1896
	// Validate Think value: string values currently only allowed for gptoss models
	if req.Think != nil && req.Think.IsString() && !useHarmony {
1897
		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
1898
1899
1900
		return
	}

1901
1902
	var thinkingState *thinking.Parser
	openingTag, closingTag := thinking.InferTags(m.Template.Template)
1903
	if req.Think != nil && req.Think.Bool() && openingTag != "" && closingTag != "" {
1904
		thinkingState = &thinking.Parser{
Devon Rifkin's avatar
Devon Rifkin committed
1905
1906
			OpeningTag: openingTag,
			ClosingTag: closingTag,
1907
		}
1908
1909
1910
1911

		if strings.HasSuffix(strings.TrimSpace(prompt), openingTag) {
			thinkingState.AddContent(openingTag)
		}
1912
1913
	}

1914
	var toolParser *tools.Parser
Michael Yang's avatar
Michael Yang committed
1915
	if len(req.Tools) > 0 && !useHarmony {
1916
		toolParser = tools.NewParser(m.Template.Template, req.Tools)
1917
1918
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
1919
1920
1921
	ch := make(chan any)
	go func() {
		defer close(ch)
1922

Michael Yang's avatar
Michael Yang committed
1923
		if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
1924
1925
1926
1927
			Prompt:  prompt,
			Images:  images,
			Format:  req.Format,
			Options: opts,
Michael Yang's avatar
Michael Yang committed
1928
		}, func(r llm.CompletionResponse) {
1929
			res := api.ChatResponse{
1930
1931
				Model:     req.Model,
				CreatedAt: time.Now().UTC(),
1932
				Message:   api.Message{Role: "assistant", Content: r.Content},
1933
				Done:      r.Done,
Bruce MacDonald's avatar
Bruce MacDonald committed
1934
1935
1936
1937
1938
1939
1940
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}
Michael Yang's avatar
Michael Yang committed
1941
1942
1943
1944
1945
1946
			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
1947
			// TODO(drifkin): fold this as much as possibleinto the generic m.Config.Parser logic
Michael Yang's avatar
Michael Yang committed
1948
			if useHarmony {
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
				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
1967
				}
1968

Michael Yang's avatar
Michael Yang committed
1969
1970
1971
1972
				// 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
				}
1973

Devon Rifkin's avatar
Devon Rifkin committed
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
				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
1995
1996
				return
			}
1997

1998
			if thinkingState != nil {
Devon Rifkin's avatar
Devon Rifkin committed
1999
				thinkingContent, remainingContent := thinkingState.AddContent(res.Message.Content)
2000
2001
2002
2003
2004
2005
2006
2007
				if thinkingContent == "" && remainingContent == "" && !r.Done {
					// need to accumulate more to decide what to send
					return
				}
				res.Message.Content = remainingContent
				res.Message.Thinking = thinkingContent
			}

2008
			if len(req.Tools) > 0 {
2009
				toolCalls, content := toolParser.Add(res.Message.Content)
2010
2011
2012
2013
2014
				if len(content) > 0 {
					res.Message.Content = content
				} else if len(toolCalls) > 0 {
					res.Message.ToolCalls = toolCalls
					res.Message.Content = ""
2015
2016
				} else if res.Message.Thinking != "" {
					// don't return
2017
2018
				} else {
					if r.Done {
2019
						res.Message.Content = toolParser.Content()
2020
2021
2022
						ch <- res
					}
					return
2023
2024
				}
			}
2025

2026
			ch <- res
Michael Yang's avatar
Michael Yang committed
2027
		}); err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
2028
2029
2030
2031
2032
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
Michael Yang's avatar
tools  
Michael Yang committed
2033
		var resp api.ChatResponse
2034
		var toolCalls []api.ToolCall
2035
2036
		var sbThinking strings.Builder
		var sbContent strings.Builder
Michael Yang's avatar
Michael Yang committed
2037
2038
		for rr := range ch {
			switch t := rr.(type) {
2039
			case api.ChatResponse:
2040
2041
				sbThinking.WriteString(t.Message.Thinking)
				sbContent.WriteString(t.Message.Content)
Michael Yang's avatar
tools  
Michael Yang committed
2042
				resp = t
2043
2044
2045
				if len(req.Tools) > 0 {
					toolCalls = append(toolCalls, t.Message.ToolCalls...)
				}
2046
			case gin.H:
Michael Yang's avatar
Michael Yang committed
2047
2048
2049
				msg, ok := t["error"].(string)
				if !ok {
					msg = "unexpected error format in response"
2050
				}
Michael Yang's avatar
Michael Yang committed
2051
2052
2053

				c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
				return
2054
			default:
Michael Yang's avatar
Michael Yang committed
2055
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
2056
				return
Bruce MacDonald's avatar
Bruce MacDonald committed
2057
2058
			}
		}
2059

2060
2061
2062
		resp.Message.Content = sbContent.String()
		resp.Message.Thinking = sbThinking.String()

2063
2064
		if len(toolCalls) > 0 {
			resp.Message.ToolCalls = toolCalls
Michael Yang's avatar
tools  
Michael Yang committed
2065
2066
2067
		}

		c.JSON(http.StatusOK, resp)
Bruce MacDonald's avatar
Bruce MacDonald committed
2068
2069
2070
2071
2072
		return
	}

	streamResponse(c, ch)
}
2073

Michael Yang's avatar
Michael Yang committed
2074
func handleScheduleError(c *gin.Context, name string, err error) {
Michael Yang's avatar
Michael Yang committed
2075
	switch {
2076
	case errors.Is(err, errCapabilities), errors.Is(err, errRequired):
Michael Yang's avatar
Michael Yang committed
2077
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
2078
	case errors.Is(err, context.Canceled):
2079
		c.JSON(499, gin.H{"error": "request canceled"})
Michael Yang's avatar
Michael Yang committed
2080
	case errors.Is(err, ErrMaxQueue):
2081
		c.JSON(http.StatusServiceUnavailable, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
2082
2083
	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
2084
2085
	default:
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
2086
2087
	}
}
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099

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 {
2100
2101
2102
2103
2104
				// 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.
2105
				thinkingState := &thinking.Parser{
Devon Rifkin's avatar
Devon Rifkin committed
2106
2107
					OpeningTag: "<think>",
					ClosingTag: "</think>",
2108
				}
Devon Rifkin's avatar
Devon Rifkin committed
2109
				_, content := thinkingState.AddContent(msg.Content)
2110
				msgs[i].Content = content
2111
2112
2113
2114
2115
			}
		}
	}
	return msgs
}