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

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

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

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

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

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

69
70
71
72
73
74
func experimentEnabled(name string) bool {
	return slices.Contains(strings.Split(os.Getenv("OLLAMA_EXPERIMENT"), ","), name)
}

var useClient2 = experimentEnabled("client2")

75
76
77
78
// 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
79
80
var mode string = gin.DebugMode

81
type Server struct {
82
83
84
	addr    net.Addr
	sched   *Scheduler
	lowVRAM bool
85
86
}

Michael Yang's avatar
Michael Yang committed
87
88
89
90
91
92
93
94
95
96
func init() {
	switch mode {
	case gin.DebugMode:
	case gin.ReleaseMode:
	case gin.TestMode:
	default:
		mode = gin.DebugMode
	}

	gin.SetMode(mode)
97
98
99

	// Tell renderers to use [img] tags
	renderers.RenderImgTags = true
Michael Yang's avatar
Michael Yang committed
100
101
}

Michael Yang's avatar
lint  
Michael Yang committed
102
103
104
105
var (
	errRequired    = errors.New("is required")
	errBadTemplate = errors.New("template error")
)
Michael Yang's avatar
Michael Yang committed
106

107
func modelOptions(model *Model, requestOpts map[string]any) (api.Options, error) {
108
109
110
111
112
113
114
115
116
117
	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
118
119
}

Michael Yang's avatar
Michael Yang committed
120
121
// 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.
122
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
123
	if name == "" {
Michael Yang's avatar
Michael Yang committed
124
		return nil, nil, nil, fmt.Errorf("model %w", errRequired)
Bruce MacDonald's avatar
Bruce MacDonald committed
125
126
	}

Michael Yang's avatar
Michael Yang committed
127
	model, err := GetModel(name)
Bruce MacDonald's avatar
Bruce MacDonald committed
128
	if err != nil {
Michael Yang's avatar
Michael Yang committed
129
		return nil, nil, nil, err
130
131
	}

132
133
134
135
	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
136
	if err := model.CheckCapabilities(caps...); err != nil {
Michael Yang's avatar
Michael Yang committed
137
		return nil, nil, nil, fmt.Errorf("%s %w", name, err)
138
139
	}

Michael Yang's avatar
Michael Yang committed
140
	opts, err := modelOptions(model, requestOpts)
141
	if err != nil {
Michael Yang's avatar
Michael Yang committed
142
		return nil, nil, nil, err
143
144
	}

145
146
	// This model is much more capable with a larger context, so set that
	// unless it would penalize performance too much
147
148
149
150
	if !s.lowVRAM && slices.Contains([]string{
		"gptoss", "gpt-oss",
		"qwen3vl", "qwen3vlmoe",
	}, model.Config.ModelFamily) {
Michael Yang's avatar
Michael Yang committed
151
152
153
		opts.NumCtx = max(opts.NumCtx, 8192)
	}

Michael Yang's avatar
Michael Yang committed
154
	runnerCh, errCh := s.sched.GetRunner(ctx, model, opts, keepAlive)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
155
156
	var runner *runnerRef
	select {
Michael Yang's avatar
Michael Yang committed
157
158
	case runner = <-runnerCh:
	case err = <-errCh:
Michael Yang's avatar
Michael Yang committed
159
		return nil, nil, nil, err
Bruce MacDonald's avatar
Bruce MacDonald committed
160
161
	}

Michael Yang's avatar
Michael Yang committed
162
	return runner.llama, model, &opts, nil
Michael Yang's avatar
Michael Yang committed
163
164
}

165
166
167
168
169
170
171
172
173
174
175
func signinURL() (string, error) {
	pubKey, err := auth.GetPublicKey()
	if err != nil {
		return "", err
	}

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

Michael Yang's avatar
Michael Yang committed
176
func (s *Server) GenerateHandler(c *gin.Context) {
177
	checkpointStart := time.Now()
Michael Yang's avatar
Michael Yang committed
178
179
180
181
182
183
	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
184
185
186
		return
	}

187
188
189
190
191
	if req.TopLogprobs < 0 || req.TopLogprobs > 20 {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "top_logprobs must be between 0 and 20"})
		return
	}

192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
	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
	}

208
	m, err := GetModel(name.String())
209
210
	if err != nil {
		switch {
211
		case errors.Is(err, fs.ErrNotExist):
212
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
213
		case err.Error() == errtypes.InvalidModelNameErrMsg:
214
215
216
217
218
219
220
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

221
222
223
224
225
	if req.TopLogprobs < 0 || req.TopLogprobs > 20 {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "top_logprobs must be between 0 and 20"})
		return
	}

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

266
267
268
269
270
271
		contentType := "application/x-ndjson"
		if req.Stream != nil && !*req.Stream {
			contentType = "application/json; charset=utf-8"
		}
		c.Header("Content-Type", contentType)

272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
		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 {
292
293
294
295
296
297
			var authError api.AuthorizationError
			if errors.As(err, &authError) {
				sURL, sErr := signinURL()
				if sErr != nil {
					slog.Error(sErr.Error())
					c.JSON(http.StatusInternalServerError, gin.H{"error": "error getting authorization details"})
298
299
					return
				}
300
301
302
303
304
305
306

				c.JSON(authError.StatusCode, gin.H{"error": "unauthorized", "signin_url": sURL})
				return
			}
			var apiError api.StatusError
			if errors.As(err, &apiError) {
				c.JSON(apiError.StatusCode, apiError)
307
308
309
310
311
312
313
314
315
				return
			}
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		return
	}

Patrick Devine's avatar
Patrick Devine committed
316
	// expire the runner
Michael Yang's avatar
Michael Yang committed
317
	if req.Prompt == "" && req.KeepAlive != nil && req.KeepAlive.Duration == 0 {
318
		s.sched.expireRunner(m)
Patrick Devine's avatar
Patrick Devine committed
319
320
321
322
323
324
325
326
327
328
329

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

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

335
336
337
338
339
340
341
342
343
	var builtinParser parsers.Parser
	if shouldUseHarmony(m) && m.Config.Parser == "" {
		m.Config.Parser = "harmony"
	}

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

348
349
	// Validate Think value: string values currently only allowed for harmony/gptoss models
	if req.Think != nil && req.Think.IsString() && m.Config.Parser != "harmony" {
350
		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
351
352
353
		return
	}

354
	caps := []model.Capability{model.CapabilityCompletion}
355
	if req.Suffix != "" {
356
		caps = append(caps, model.CapabilityInsert)
357
	}
358
359

	modelCaps := m.Capabilities()
360
	if slices.Contains(modelCaps, model.CapabilityThinking) {
361
		caps = append(caps, model.CapabilityThinking)
362
		if req.Think == nil {
363
364
			req.Think = &api.ThinkValue{Value: true}
		}
365
366
367
368
369
	} else {
		if req.Think != nil && req.Think.Bool() {
			c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("%q does not support thinking", req.Model)})
			return
		}
370
	}
371

372
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), caps, req.Options, req.KeepAlive)
Michael Yang's avatar
Michael Yang committed
373
374
375
376
	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
377
378
379
380
		handleScheduleError(c, req.Model, err)
		return
	}

381
382
	checkpointLoaded := time.Now()

383
	// load the model
Michael Yang's avatar
Michael Yang committed
384
385
386
387
388
389
390
	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
391
392
		return
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
393

394
395
	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"})
396
397
398
		return
	}

Michael Yang's avatar
Michael Yang committed
399
400
	images := make([]llm.ImageData, len(req.Images))
	for i := range req.Images {
401
		images[i] = llm.ImageData{ID: i, Data: req.Images[i]}
Michael Yang's avatar
Michael Yang committed
402
	}
Bruce MacDonald's avatar
Bruce MacDonald committed
403

Michael Yang's avatar
Michael Yang committed
404
405
	prompt := req.Prompt
	if !req.Raw {
Michael Yang's avatar
Michael Yang committed
406
		tmpl := m.Template
Michael Yang's avatar
Michael Yang committed
407
408
409
410
411
412
413
414
		if req.Template != "" {
			tmpl, err = template.Parse(req.Template)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}

415
416
417
418
419
420
421
422
423
424
425
426
		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
427
428
429
430
			if req.Context == nil {
				msgs = append(msgs, m.Messages...)
			}

431
			userMsg := api.Message{Role: "user", Content: req.Prompt}
432
			for _, i := range images {
433
				userMsg.Images = append(userMsg.Images, i.Data)
434
			}
435
			values.Messages = append(msgs, userMsg)
436
437
		}

438
		values.Think = req.Think != nil && req.Think.Bool()
Michael Yang's avatar
Michael Yang committed
439
440
		values.ThinkLevel = ""
		if req.Think != nil {
441
			values.ThinkLevel = req.Think.String()
Michael Yang's avatar
Michael Yang committed
442
		}
443
444
		values.IsThinkSet = req.Think != nil

Michael Yang's avatar
Michael Yang committed
445
446
		var b bytes.Buffer
		if req.Context != nil {
447
			slog.Warn("the context field is deprecated and will be removed in a future version of Ollama")
448
			s, err := r.Detokenize(c.Request.Context(), req.Context)
Michael Yang's avatar
Michael Yang committed
449
450
451
452
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
453
			b.WriteString(s)
Michael Yang's avatar
Michael Yang committed
454
		}
455

456
457
458
459
460
461
		// check that we're in the `api/chat`-like flow, and if so, generate the
		// prompt the same way
		// TEMP(drifkin): we should really just detect the chat-like flow and call
		// the real chat handler, but doing this as a stopgap to get renderer
		// support for generate
		if values.Messages != nil && values.Suffix == "" && req.Template == "" {
462
			prompt, images, err = chatPrompt(c.Request.Context(), m, r.Tokenize, opts, values.Messages, []api.Tool{}, req.Think, req.Truncate == nil || *req.Truncate)
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
			// TEMP(drifkin): req.Context will be removed very soon, but we're temporarily supporting it in this flow here
			if req.Context != nil {
				b.WriteString(prompt)
				prompt = b.String()
			}
		} else {
			// legacy flow
			if err := tmpl.Execute(&b, values); err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
478

479
480
			prompt = b.String()
		}
Bruce MacDonald's avatar
Bruce MacDonald committed
481
482
	}

483
484
	// If debug mode is enabled, return the rendered template instead of calling the model
	if req.DebugRenderOnly {
Devon Rifkin's avatar
Devon Rifkin committed
485
		c.JSON(http.StatusOK, api.GenerateResponse{
486
487
			Model:     req.Model,
			CreatedAt: time.Now().UTC(),
Devon Rifkin's avatar
Devon Rifkin committed
488
			DebugInfo: &api.DebugInfo{
489
490
491
492
493
494
495
				RenderedTemplate: prompt,
				ImageCount:       len(images),
			},
		})
		return
	}

496
	var thinkingState *thinking.Parser
497
	if builtinParser == nil {
Michael Yang's avatar
Michael Yang committed
498
		openingTag, closingTag := thinking.InferTags(m.Template.Template)
499
		if req.Think != nil && req.Think.Bool() && openingTag != "" && closingTag != "" {
Michael Yang's avatar
Michael Yang committed
500
501
502
503
			thinkingState = &thinking.Parser{
				OpeningTag: openingTag,
				ClosingTag: closingTag,
			}
504
505
506
			if strings.HasSuffix(strings.TrimSpace(prompt), openingTag) {
				thinkingState.AddContent(openingTag)
			}
507
508
509
		}
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
510
511
	ch := make(chan any)
	go func() {
512
513
		// TODO (jmorganca): avoid building the response twice both here and below
		var sb strings.Builder
Bruce MacDonald's avatar
Bruce MacDonald committed
514
		defer close(ch)
Michael Yang's avatar
Michael Yang committed
515
		if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
516
517
518
519
520
521
522
523
			Prompt:      prompt,
			Images:      images,
			Format:      req.Format,
			Options:     opts,
			Shift:       req.Shift == nil || *req.Shift,
			Truncate:    req.Truncate == nil || *req.Truncate,
			Logprobs:    req.Logprobs,
			TopLogprobs: req.TopLogprobs,
524
525
		}, func(cr llm.CompletionResponse) {
			res := api.GenerateResponse{
526
527
528
529
				Model:     req.Model,
				CreatedAt: time.Now().UTC(),
				Response:  cr.Content,
				Done:      cr.Done,
Bruce MacDonald's avatar
Bruce MacDonald committed
530
				Metrics: api.Metrics{
531
532
533
534
					PromptEvalCount:    cr.PromptEvalCount,
					PromptEvalDuration: cr.PromptEvalDuration,
					EvalCount:          cr.EvalCount,
					EvalDuration:       cr.EvalDuration,
Bruce MacDonald's avatar
Bruce MacDonald committed
535
				},
536
				Logprobs: toAPILogprobs(cr.Logprobs),
Bruce MacDonald's avatar
Bruce MacDonald committed
537
			}
538

539
540
541
542
543
544
			if builtinParser != nil {
				content, thinking, toolCalls, err := builtinParser.Add(cr.Content, cr.Done)
				if err != nil {
					ch <- gin.H{"error": err.Error()}
					return
				}
545
546
				res.Response = content
				res.Thinking = thinking
547
548
549
				if cr.Done && len(toolCalls) > 0 {
					res.ToolCalls = toolCalls
				}
550
			} else if thinkingState != nil {
Devon Rifkin's avatar
Devon Rifkin committed
551
				thinking, content := thinkingState.AddContent(cr.Content)
552
553
554
555
				res.Thinking = thinking
				res.Response = content
			}

556
557
558
559
560
			if _, err := sb.WriteString(cr.Content); err != nil {
				ch <- gin.H{"error": err.Error()}
			}

			if cr.Done {
561
562
563
564
				res.DoneReason = cr.DoneReason.String()
				res.TotalDuration = time.Since(checkpointStart)
				res.LoadDuration = checkpointLoaded.Sub(checkpointStart)

565
				if !req.Raw {
566
					tokens, err := r.Tokenize(c.Request.Context(), prompt+sb.String())
567
568
569
570
					if err != nil {
						ch <- gin.H{"error": err.Error()}
						return
					}
571
					res.Context = tokens
572
573
574
				}
			}

575
			if builtinParser != nil {
Michael Yang's avatar
Michael Yang committed
576
577
578
579
580
581
582
583
				// only send messages with meaningful content (empty messages confuse clients)
				if res.Response != "" || res.Thinking != "" || res.Done || len(res.ToolCalls) > 0 {
					ch <- res
				}

				return
			}

584
			ch <- res
Michael Yang's avatar
Michael Yang committed
585
		}); err != nil {
586
587
588
589
590
591
			var serr api.StatusError
			if errors.As(err, &serr) {
				ch <- gin.H{"error": serr.ErrorMessage, "status": serr.StatusCode}
			} else {
				ch <- gin.H{"error": err.Error()}
			}
Bruce MacDonald's avatar
Bruce MacDonald committed
592
593
594
595
		}
	}()

	if req.Stream != nil && !*req.Stream {
Michael Yang's avatar
Michael Yang committed
596
		var r api.GenerateResponse
597
		var allLogprobs []api.Logprob
598
599
		var sbThinking strings.Builder
		var sbContent strings.Builder
Michael Yang's avatar
Michael Yang committed
600
601
		for rr := range ch {
			switch t := rr.(type) {
602
			case api.GenerateResponse:
603
604
				sbThinking.WriteString(t.Thinking)
				sbContent.WriteString(t.Response)
Michael Yang's avatar
Michael Yang committed
605
				r = t
606
607
608
609
				// Accumulate logprobs from all chunks for non-streaming response
				if len(t.Logprobs) > 0 {
					allLogprobs = append(allLogprobs, t.Logprobs...)
				}
610
611
612
613
614
615
			case gin.H:
				msg, ok := t["error"].(string)
				if !ok {
					msg = "unexpected error format in response"
				}

616
617
618
619
620
621
				status, ok := t["status"].(int)
				if !ok {
					status = http.StatusInternalServerError
				}

				c.JSON(status, gin.H{"error": msg})
Michael Yang's avatar
Michael Yang committed
622
				return
623
			default:
Michael Yang's avatar
Michael Yang committed
624
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
Bruce MacDonald's avatar
Bruce MacDonald committed
625
626
627
				return
			}
		}
628

629
630
		r.Thinking = sbThinking.String()
		r.Response = sbContent.String()
631
		r.Logprobs = allLogprobs
632

Michael Yang's avatar
Michael Yang committed
633
		c.JSON(http.StatusOK, r)
Bruce MacDonald's avatar
Bruce MacDonald committed
634
635
636
637
638
639
		return
	}

	streamResponse(c, ch)
}

640
func (s *Server) EmbedHandler(c *gin.Context) {
641
	checkpointStart := time.Now()
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
	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
	}

	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:
669
670
671
672
		if req.Input != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid input type"})
			return
		}
673
674
	}

675
676
677
678
679
680
	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
	}

681
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), []model.Capability{}, req.Options, req.KeepAlive)
682
683
684
685
686
	if err != nil {
		handleScheduleError(c, req.Model, err)
		return
	}

687
688
	checkpointLoaded := time.Now()

689
690
691
692
693
	if len(input) == 0 {
		c.JSON(http.StatusOK, api.EmbedResponse{Model: req.Model, Embeddings: [][]float32{}})
		return
	}

694
695
696
697
698
699
	kvData, _, err := getModelData(m.ModelPath, false)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

700
	ctx := c.Request.Context()
701

702
703
704
705
706
	embedWithRetry := func(text string) ([]float32, int, error) {
		emb, tokCount, err := r.Embedding(ctx, text)
		if err == nil {
			return emb, tokCount, nil
		}
707

708
709
710
711
712
713
714
		var serr api.StatusError
		if !errors.As(err, &serr) || serr.StatusCode != http.StatusBadRequest {
			return nil, 0, err
		}
		if req.Truncate != nil && !*req.Truncate {
			return nil, 0, err
		}
715

716
717
718
719
		tokens, err := r.Tokenize(ctx, text)
		if err != nil {
			return nil, 0, err
		}
720

721
722
723
724
725
726
727
		// TODO @nicolepardal: avoid reaching into kvData here; pass required tokenizer metadata via model/options instead
		ctxLen := min(opts.NumCtx, int(kvData.ContextLength()))
		if bos := kvData.Uint("tokenizer.ggml.bos_token_id"); len(tokens) > 0 && tokens[0] != int(bos) && kvData.Bool("add_bos_token", true) {
			ctxLen--
		}
		if eos := kvData.Uint("tokenizer.ggml.eos_token_id"); len(tokens) > 0 && tokens[len(tokens)-1] != int(eos) && kvData.Bool("add_eos_token", true) {
			ctxLen--
728
729
		}

730
731
732
733
734
735
		if len(tokens) <= ctxLen {
			return nil, 0, fmt.Errorf("input exceeds maximum context length and cannot be truncated further")
		}
		if ctxLen <= 0 {
			return nil, 0, fmt.Errorf("input after truncation exceeds maximum context length")
		}
736

737
738
739
740
741
742
		truncatedTokens := tokens[:ctxLen]
		truncated, err := r.Detokenize(ctx, truncatedTokens)
		if err != nil {
			return nil, 0, err
		}
		return r.Embedding(ctx, truncated)
743
744
	}

745
746
	var g errgroup.Group
	embeddings := make([][]float32, len(input))
747
	var totalTokens uint64
748
749
	for i, text := range input {
		g.Go(func() error {
750
			embedding, tokenCount, err := embedWithRetry(text)
751
752
753
			if err != nil {
				return err
			}
754
755
756
757
758
759
			// 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
760
			atomic.AddUint64(&totalTokens, uint64(tokenCount))
761
762
			return nil
		})
763
764
	}

765
	if err := g.Wait(); err != nil {
766
767
768
769
770
771
772
773
774
775
776
		var serr api.StatusError
		if errors.As(err, &serr) {
			c.AbortWithStatusJSON(serr.StatusCode, gin.H{
				"error": strings.TrimSpace(serr.ErrorMessage),
			})
			return
		}

		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
			"error": strings.TrimSpace(err.Error()),
		})
777
		return
778
779
780
	}

	resp := api.EmbedResponse{
781
		Model:           req.Model,
782
		Embeddings:      embeddings,
783
784
		TotalDuration:   time.Since(checkpointStart),
		LoadDuration:    checkpointLoaded.Sub(checkpointStart),
785
		PromptEvalCount: int(totalTokens),
786
787
788
789
790
791
792
793
794
795
	}
	c.JSON(http.StatusOK, resp)
}

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

796
	norm := float32(1.0 / max(math.Sqrt(float64(sum)), 1e-12))
797
798
799
800
801
802
	for i := range vec {
		vec[i] *= norm
	}
	return vec
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
803
func (s *Server) EmbeddingsHandler(c *gin.Context) {
Bruce MacDonald's avatar
Bruce MacDonald committed
804
	var req api.EmbeddingRequest
Michael Yang's avatar
Michael Yang committed
805
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
Bruce MacDonald's avatar
Bruce MacDonald committed
806
807
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
808
	} else if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
809
810
811
812
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

813
814
815
816
817
818
	name := model.ParseName(req.Model)
	if !name.IsValid() {
		c.JSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
	}

819
	r, _, _, err := s.scheduleRunner(c.Request.Context(), name.String(), []model.Capability{}, req.Options, req.KeepAlive)
Bruce MacDonald's avatar
Bruce MacDonald committed
820
	if err != nil {
Michael Yang's avatar
Michael Yang committed
821
		handleScheduleError(c, req.Model, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
822
823
824
		return
	}

825
826
827
	// an empty request loads the model
	if req.Prompt == "" {
		c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: []float64{}})
Bruce MacDonald's avatar
Bruce MacDonald committed
828
829
830
		return
	}

831
	embedding, _, err := r.Embedding(c.Request.Context(), req.Prompt)
Bruce MacDonald's avatar
Bruce MacDonald committed
832
	if err != nil {
833
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": strings.TrimSpace(err.Error())})
Bruce MacDonald's avatar
Bruce MacDonald committed
834
835
836
		return
	}

837
838
839
	var e []float64
	for _, v := range embedding {
		e = append(e, float64(v))
840
841
842
	}

	resp := api.EmbeddingResponse{
843
		Embedding: e,
844
845
	}
	c.JSON(http.StatusOK, resp)
Bruce MacDonald's avatar
Bruce MacDonald committed
846
847
}

848
func (s *Server) PullHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
849
	var req api.PullRequest
Michael Yang's avatar
Michael Yang committed
850
851
852
853
854
855
856
	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
857
858
859
		return
	}

860
861
	name := model.ParseName(cmp.Or(req.Model, req.Name))
	if !name.IsValid() {
862
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": errtypes.InvalidModelNameErrMsg})
863
864
865
		return
	}

866
867
	name, err = getExistingName(name)
	if err != nil {
868
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
869
870
871
		return
	}

872
873
874
	ch := make(chan any)
	go func() {
		defer close(ch)
875
876
		fn := func(r api.ProgressResponse) {
			ch <- r
877
		}
878

Michael Yang's avatar
Michael Yang committed
879
		regOpts := &registryOptions{
880
881
882
			Insecure: req.Insecure,
		}

883
884
885
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

886
		if err := PullModel(ctx, name.DisplayShortest(), regOpts, fn); err != nil {
Michael Yang's avatar
Michael Yang committed
887
			ch <- gin.H{"error": err.Error()}
888
889
890
		}
	}()

891
892
893
894
895
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

896
897
898
	streamResponse(c, ch)
}

899
func (s *Server) PushHandler(c *gin.Context) {
900
	var req api.PushRequest
Michael Yang's avatar
Michael Yang committed
901
902
903
904
905
906
907
	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
908
909
		return
	}
Michael Yang's avatar
Michael Yang committed
910

911
	var mname string
Michael Yang's avatar
Michael Yang committed
912
	if req.Model != "" {
913
		mname = req.Model
Michael Yang's avatar
Michael Yang committed
914
	} else if req.Name != "" {
915
		mname = req.Name
Michael Yang's avatar
Michael Yang committed
916
917
	} else {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
918
919
920
		return
	}

921
922
923
	ch := make(chan any)
	go func() {
		defer close(ch)
924
925
		fn := func(r api.ProgressResponse) {
			ch <- r
926
		}
927

Michael Yang's avatar
Michael Yang committed
928
		regOpts := &registryOptions{
929
930
931
			Insecure: req.Insecure,
		}

Michael Yang's avatar
Michael Yang committed
932
933
934
		ctx, cancel := context.WithCancel(c.Request.Context())
		defer cancel()

935
936
937
938
939
940
941
		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
942
			ch <- gin.H{"error": err.Error()}
943
944
945
		}
	}()

946
947
948
949
950
	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

951
952
953
	streamResponse(c, ch)
}

954
955
956
957
// 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.
958
959
960
func getExistingName(n model.Name) (model.Name, error) {
	var zero model.Name
	existing, err := Manifests(true)
961
	if err != nil {
962
		return zero, err
963
	}
964
	var set model.Name // tracks parts already canonicalized
965
	for e := range existing {
966
967
968
969
970
971
972
973
974
975
976
		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
977
978
		}
	}
979
	return n, nil
980
981
}

982
func (s *Server) DeleteHandler(c *gin.Context) {
983
984
	var r api.DeleteRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
985
986
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
987
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
988
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
989
990
991
		return
	}

992
993
994
	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))})
995
996
		return
	}
Michael Yang's avatar
Michael Yang committed
997

998
999
1000
1001
1002
1003
	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
	}

1004
	m, err := ParseNamedManifest(n)
Michael Yang's avatar
Michael Yang committed
1005
	if err != nil {
1006
1007
1008
1009
1010
1011
		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
1012
1013
1014
		return
	}

1015
	if err := m.Remove(); err != nil {
Michael Yang's avatar
Michael Yang committed
1016
1017
1018
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
1019
1020
1021
1022
1023

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

1026
func (s *Server) ShowHandler(c *gin.Context) {
Patrick Devine's avatar
Patrick Devine committed
1027
	var req api.ShowRequest
Michael Yang's avatar
Michael Yang committed
1028
1029
1030
1031
1032
1033
1034
	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
1035
1036
1037
		return
	}

Michael Yang's avatar
Michael Yang committed
1038
	if req.Model != "" {
Michael Yang's avatar
Michael Yang committed
1039
		// noop
Michael Yang's avatar
Michael Yang committed
1040
	} else if req.Name != "" {
Michael Yang's avatar
Michael Yang committed
1041
		req.Model = req.Name
Michael Yang's avatar
Michael Yang committed
1042
	} else {
1043
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
1044
1045
1046
		return
	}

1047
	resp, err := GetModelInfo(req)
Patrick Devine's avatar
Patrick Devine committed
1048
	if err != nil {
1049
1050
		switch {
		case os.IsNotExist(err):
Michael Yang's avatar
Michael Yang committed
1051
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
1052
		case err.Error() == errtypes.InvalidModelNameErrMsg:
1053
1054
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
Patrick Devine's avatar
Patrick Devine committed
1055
1056
1057
1058
1059
1060
1061
1062
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

	c.JSON(http.StatusOK, resp)
}

1063
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
1064
1065
	name := model.ParseName(req.Model)
	if !name.IsValid() {
CYJiang's avatar
CYJiang committed
1066
		return nil, ErrModelPathInvalid
1067
1068
1069
1070
1071
1072
1073
	}
	name, err := getExistingName(name)
	if err != nil {
		return nil, err
	}

	m, err := GetModel(name.String())
Patrick Devine's avatar
Patrick Devine committed
1074
1075
1076
1077
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
1078
	modelDetails := api.ModelDetails{
1079
1080
1081
1082
1083
1084
		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
1085
1086
	}

1087
	if req.System != "" {
1088
		m.System = req.System
1089
1090
	}

Michael Yang's avatar
Michael Yang committed
1091
1092
1093
	msgs := make([]api.Message, len(m.Messages))
	for i, msg := range m.Messages {
		msgs[i] = api.Message{Role: msg.Role, Content: msg.Content}
1094
1095
	}

1096
	manifest, err := ParseNamedManifest(name)
1097
1098
1099
1100
	if err != nil {
		return nil, err
	}

Patrick Devine's avatar
Patrick Devine committed
1101
	resp := &api.ShowResponse{
1102
1103
1104
1105
1106
1107
1108
		License:      strings.Join(m.License, "\n"),
		System:       m.System,
		Template:     m.Template.String(),
		Details:      modelDetails,
		Messages:     msgs,
		Capabilities: m.Capabilities(),
		ModifiedAt:   manifest.fi.ModTime(),
1109
		Requires:     m.Config.Requires,
Patrick Devine's avatar
Patrick Devine committed
1110
1111
	}

1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
	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
1134
1135
	var params []string
	cs := 30
1136
	for k, v := range m.Options {
Patrick Devine's avatar
Patrick Devine committed
1137
		switch val := v.(type) {
1138
		case []any:
Patrick Devine's avatar
Patrick Devine committed
1139
			for _, nv := range val {
Patrick Devine's avatar
Patrick Devine committed
1140
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
Patrick Devine's avatar
Patrick Devine committed
1141
			}
Patrick Devine's avatar
Patrick Devine committed
1142
1143
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
Patrick Devine's avatar
Patrick Devine committed
1144
1145
1146
1147
		}
	}
	resp.Parameters = strings.Join(params, "\n")

Patrick Devine's avatar
Patrick Devine committed
1148
1149
1150
1151
1152
	if len(req.Options) > 0 {
		if m.Options == nil {
			m.Options = make(map[string]any)
		}
		for k, v := range req.Options {
1153
			m.Options[k] = v
1154
1155
1156
		}
	}

1157
	var sb strings.Builder
1158
	fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"")
1159
	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
1160
1161
	fmt.Fprintf(&sb, "# FROM %s\n\n", m.ShortName)
	fmt.Fprint(&sb, m.String())
1162
	resp.Modelfile = sb.String()
1163

1164
1165
1166
1167
1168
	// skip loading tensor information if this is a remote model
	if m.Config.RemoteHost != "" && m.Config.RemoteModel != "" {
		return resp, nil
	}

1169
	kvData, tensors, err := getModelData(m.ModelPath, req.Verbose)
1170
1171
1172
	if err != nil {
		return nil, err
	}
1173

1174
1175
1176
1177
	delete(kvData, "general.name")
	delete(kvData, "tokenizer.chat_template")
	resp.ModelInfo = kvData

1178
1179
1180
1181
1182
1183
	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

1184
	if len(m.ProjectorPaths) > 0 {
1185
		projectorData, _, err := getModelData(m.ProjectorPaths[0], req.Verbose)
1186
1187
1188
1189
1190
1191
		if err != nil {
			return nil, err
		}
		resp.ProjectorInfo = projectorData
	}

Patrick Devine's avatar
Patrick Devine committed
1192
1193
1194
	return resp, nil
}

1195
func getModelData(digest string, verbose bool) (ggml.KV, ggml.Tensors, error) {
1196
1197
1198
1199
	maxArraySize := 0
	if verbose {
		maxArraySize = -1
	}
1200
	data, err := llm.LoadModel(digest, maxArraySize)
1201
	if err != nil {
1202
		return nil, ggml.Tensors{}, err
1203
1204
	}

1205
	kv := data.KV()
1206
1207
1208
1209
1210
1211
1212
1213
1214

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

1215
	return kv, data.Tensors(), nil
1216
1217
}

1218
func (s *Server) ListHandler(c *gin.Context) {
1219
	ms, err := Manifests(true)
Patrick Devine's avatar
Patrick Devine committed
1220
1221
1222
1223
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Michael Yang's avatar
Michael Yang committed
1224

1225
	models := []api.ListModelResponse{}
1226
	for n, m := range ms {
1227
		var cf model.ConfigV2
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240

		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
1241
		}
Michael Yang's avatar
Michael Yang committed
1242

1243
1244
		// tag should never be masked
		models = append(models, api.ListModelResponse{
1245
1246
1247
1248
1249
1250
1251
			Model:       n.DisplayShortest(),
			Name:        n.DisplayShortest(),
			RemoteModel: cf.RemoteModel,
			RemoteHost:  cf.RemoteHost,
			Size:        m.Size(),
			Digest:      m.digest,
			ModifiedAt:  m.fi.ModTime(),
1252
1253
1254
1255
1256
1257
1258
			Details: api.ModelDetails{
				Format:            cf.ModelFormat,
				Family:            cf.ModelFamily,
				Families:          cf.ModelFamilies,
				ParameterSize:     cf.ModelType,
				QuantizationLevel: cf.FileType,
			},
1259
		})
Patrick Devine's avatar
Patrick Devine committed
1260
1261
	}

1262
	slices.SortStableFunc(models, func(i, j api.ListModelResponse) int {
1263
1264
1265
1266
		// most recently modified first
		return cmp.Compare(j.ModifiedAt.Unix(), i.ModifiedAt.Unix())
	})

Michael Yang's avatar
Michael Yang committed
1267
	c.JSON(http.StatusOK, api.ListResponse{Models: models})
Patrick Devine's avatar
Patrick Devine committed
1268
1269
}

1270
func (s *Server) CopyHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1271
1272
	var r api.CopyRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
Michael Yang's avatar
Michael Yang committed
1273
1274
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
1275
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
1276
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Patrick Devine's avatar
Patrick Devine committed
1277
1278
1279
		return
	}

Michael Yang's avatar
Michael Yang committed
1280
1281
	src := model.ParseName(r.Source)
	if !src.IsValid() {
Michael Yang's avatar
Michael Yang committed
1282
1283
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("source %q is invalid", r.Source)})
		return
1284
	}
1285
1286
1287
1288
1289
	src, err := getExistingName(src)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
1290

Michael Yang's avatar
Michael Yang committed
1291
1292
	dst := model.ParseName(r.Destination)
	if !dst.IsValid() {
1293
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("destination %q is invalid", r.Destination)})
Patrick Devine's avatar
Patrick Devine committed
1294
1295
		return
	}
1296
1297
	dst, err = getExistingName(dst)
	if err != nil {
1298
1299
1300
1301
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

Michael Yang's avatar
Michael Yang committed
1302
1303
1304
1305
1306
	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
1307
1308
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1309
func (s *Server) HeadBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
	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
1321
	c.Status(http.StatusOK)
Michael Yang's avatar
Michael Yang committed
1322
1323
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1324
func (s *Server) CreateBlobHandler(c *gin.Context) {
Michael Yang's avatar
Michael Yang committed
1325
1326
	if ib, ok := intermediateBlobs[c.Param("digest")]; ok {
		p, err := GetBlobsPath(ib)
1327
1328
1329
1330
1331
1332
		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
1333
1334
			slog.Info("evicting intermediate blob which no longer exists", "digest", ib)
			delete(intermediateBlobs, c.Param("digest"))
1335
1336
1337
1338
1339
1340
1341
1342
1343
		} else if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		} else {
			c.Status(http.StatusOK)
			return
		}
	}

1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
	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
	}

1362
	layer, err := NewLayer(c.Request.Body, "")
Michael Yang's avatar
Michael Yang committed
1363
1364
1365
1366
1367
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

1368
1369
	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
1370
1371
1372
		return
	}

Michael Yang's avatar
Michael Yang committed
1373
	c.Status(http.StatusCreated)
Michael Yang's avatar
Michael Yang committed
1374
1375
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
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
}

1397
func allowedHost(host string) bool {
1398
1399
	host = strings.ToLower(host)

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1400
	if host == "" || host == "localhost" {
1401
1402
1403
		return true
	}

1404
	if hostname, err := os.Hostname(); err == nil && host == strings.ToLower(hostname) {
1405
1406
1407
		return true
	}

Michael Yang's avatar
lint  
Michael Yang committed
1408
	tlds := []string{
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1409
1410
1411
		"localhost",
		"local",
		"internal",
1412
	}
1413

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1414
	// check if the host is a local TLD
1415
1416
1417
1418
1419
1420
	for _, tld := range tlds {
		if strings.HasSuffix(host, "."+tld) {
			return true
		}
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1421
	return false
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1422
}
1423

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1424
1425
1426
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
	return func(c *gin.Context) {
		if addr == nil {
1427
1428
1429
1430
			c.Next()
			return
		}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1431
		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
1432
1433
1434
1435
1436
1437
1438
1439
1440
			c.Next()
			return
		}

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

Jeffrey Morgan's avatar
Jeffrey Morgan committed
1441
		if addr, err := netip.ParseAddr(host); err == nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1442
			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1443
1444
1445
1446
1447
				c.Next()
				return
			}
		}

1448
		if allowedHost(host) {
Michael Yang's avatar
lint  
Michael Yang committed
1449
			if c.Request.Method == http.MethodOptions {
1450
1451
1452
1453
				c.AbortWithStatus(http.StatusNoContent)
				return
			}

1454
1455
1456
1457
1458
1459
			c.Next()
			return
		}

		c.AbortWithStatus(http.StatusForbidden)
	}
1460
}
1461

1462
func (s *Server) GenerateRoutes(rc *ollama.Registry) (http.Handler, error) {
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
	corsConfig := cors.DefaultConfig()
	corsConfig.AllowWildcard = true
	corsConfig.AllowBrowserExtensions = true
	corsConfig.AllowHeaders = []string{
		"Authorization",
		"Content-Type",
		"User-Agent",
		"Accept",
		"X-Requested-With",

		// OpenAI compatibility headers
1474
1475
1476
1477
1478
		"OpenAI-Beta",
		"x-stainless-arch",
		"x-stainless-async",
		"x-stainless-custom-poll-interval",
		"x-stainless-helper-method",
1479
1480
		"x-stainless-lang",
		"x-stainless-os",
1481
1482
		"x-stainless-package-version",
		"x-stainless-poll-helper",
1483
1484
1485
1486
1487
1488
		"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
1489

Bruce MacDonald's avatar
Bruce MacDonald committed
1490
	r := gin.Default()
1491
	r.HandleMethodNotAllowed = true
1492
	r.Use(
1493
		cors.New(corsConfig),
1494
		allowedHostsMiddleware(s.addr),
1495
	)
Bruce MacDonald's avatar
Bruce MacDonald committed
1496

1497
1498
1499
1500
1501
1502
	// 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}) })

1503
	// Local model cache management (new implementation is at end of function)
1504
1505
	r.POST("/api/pull", s.PullHandler)
	r.POST("/api/push", s.PushHandler)
1506
1507
	r.HEAD("/api/tags", s.ListHandler)
	r.GET("/api/tags", s.ListHandler)
1508
	r.POST("/api/show", s.ShowHandler)
1509
	r.DELETE("/api/delete", s.DeleteHandler)
1510

1511
1512
	r.POST("/api/me", s.WhoamiHandler)

1513
1514
1515
1516
	r.POST("/api/signout", s.SignoutHandler)
	// deprecated
	r.DELETE("/api/user/keys/:encodedKey", s.SignoutHandler)

1517
1518
	// Create
	r.POST("/api/create", s.CreateHandler)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1519
1520
	r.POST("/api/blobs/:digest", s.CreateBlobHandler)
	r.HEAD("/api/blobs/:digest", s.HeadBlobHandler)
1521
1522
1523
	r.POST("/api/copy", s.CopyHandler)

	// Inference
1524
	r.GET("/api/ps", s.PsHandler)
1525
1526
1527
1528
	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
1529

1530
	// Inference (OpenAI compatibility)
1531
1532
1533
1534
1535
	r.POST("/v1/chat/completions", middleware.ChatMiddleware(), s.ChatHandler)
	r.POST("/v1/completions", middleware.CompletionsMiddleware(), s.GenerateHandler)
	r.POST("/v1/embeddings", middleware.EmbeddingsMiddleware(), s.EmbedHandler)
	r.GET("/v1/models", middleware.ListMiddleware(), s.ListHandler)
	r.GET("/v1/models/:model", middleware.RetrieveMiddleware(), s.ShowHandler)
1536
	r.POST("/v1/responses", middleware.ResponsesMiddleware(), s.ChatHandler)
1537

1538
1539
1540
1541
1542
1543
	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,
1544

1545
1546
1547
			Prune: PruneLayers,
		}
		return rs, nil
1548
1549
	}

1550
	return r, nil
1551
1552
1553
}

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

1557
1558
1559
1560
1561
1562
1563
1564
	blobsDir, err := GetBlobsPath("")
	if err != nil {
		return err
	}
	if err := fixBlobs(blobsDir); err != nil {
		return err
	}

Michael Yang's avatar
bool  
Michael Yang committed
1565
	if !envconfig.NoPrune() {
1566
1567
1568
1569
1570
1571
1572
		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
			}
1573

1574
1575
1576
1577
			manifestsPath, err := GetManifestPath()
			if err != nil {
				return err
			}
1578

1579
1580
1581
			if err := PruneDirectory(manifestsPath); err != nil {
				return err
			}
1582
1583
1584
		}
	}

1585
1586
	s := &Server{addr: ln.Addr()}

1587
1588
1589
1590
1591
1592
1593
	var rc *ollama.Registry
	if useClient2 {
		var err error
		rc, err = ollama.DefaultRegistry()
		if err != nil {
			return err
		}
1594
1595
	}

1596
	h, err := s.GenerateRoutes(rc)
1597
1598
1599
	if err != nil {
		return err
	}
1600

1601
1602
	http.Handle("/", h)

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1603
	ctx, done := context.WithCancel(context.Background())
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1604
1605
	schedCtx, schedDone := context.WithCancel(ctx)
	sched := InitScheduler(schedCtx)
1606
	s.sched = sched
1607

1608
	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
1609
	srvr := &http.Server{
1610
1611
1612
1613
1614
1615
1616
1617
1618
		// 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
1619
1620
	}

1621
1622
	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
1623
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
1624
1625
	go func() {
		<-signals
1626
		srvr.Close()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1627
		schedDone()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1628
		sched.unloadAllRunners()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1629
		done()
1630
1631
	}()

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1632
	s.sched.Run(schedCtx)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1633

1634
1635
1636
1637
	// 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
1638
1639
	// 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
1640
1641
	gpus := discover.GPUDevices(ctx, nil)
	discover.LogDetails(gpus)
1642

1643
1644
1645
1646
1647
1648
1649
1650
1651
	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
1652
1653
1654
1655
1656
1657
1658
	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()
1659
	return nil
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1660
}
Michael Yang's avatar
Michael Yang committed
1661

1662
func waitForStream(c *gin.Context, ch chan any) {
1663
	c.Header("Content-Type", "application/json")
1664
	var latest api.ProgressResponse
1665
1666
1667
	for resp := range ch {
		switch r := resp.(type) {
		case api.ProgressResponse:
1668
			latest = r
1669
		case gin.H:
Josh's avatar
Josh committed
1670
1671
1672
1673
			status, ok := r["status"].(int)
			if !ok {
				status = http.StatusInternalServerError
			}
1674
1675
1676
			errorMsg, ok := r["error"].(string)
			if !ok {
				errorMsg = "unknown error"
1677
			}
1678
1679
			c.JSON(status, gin.H{"error": errorMsg})
			return
1680
		default:
1681
			c.JSON(http.StatusInternalServerError, gin.H{"error": "unknown message type"})
1682
1683
1684
			return
		}
	}
1685
1686

	c.JSON(http.StatusOK, latest)
1687
1688
}

Michael Yang's avatar
Michael Yang committed
1689
func streamResponse(c *gin.Context, ch chan any) {
1690
	c.Header("Content-Type", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
1691
1692
1693
1694
1695
1696
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
		// errors are provided as a gin.H with an "error" field and
		// an optional "status" field.  For errors that are streamed
		// before any content, we need to set the status code and
		// content type for the error.
		if h, ok := val.(gin.H); ok {
			if e, ok := h["error"].(string); ok {
				status, ok := h["status"].(int)
				if !ok {
					status = http.StatusInternalServerError
				}

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

				return false
			}
		}

Michael Yang's avatar
Michael Yang committed
1721
1722
		bts, err := json.Marshal(val)
		if err != nil {
1723
			slog.Info(fmt.Sprintf("streamResponse: json.Marshal failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1724
1725
1726
			return false
		}

1727
		// Delineate chunks with new-line delimiter
Michael Yang's avatar
Michael Yang committed
1728
1729
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
1730
			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
Michael Yang's avatar
Michael Yang committed
1731
1732
1733
1734
1735
1736
			return false
		}

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

1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
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())
	}
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765

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

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

1766
1767
1768
1769
	c.JSON(http.StatusOK, user)
}

func (s *Server) SignoutHandler(c *gin.Context) {
1770
1771
1772
1773
1774
1775
1776
1777
	pubKey, err := auth.GetPublicKey()
	if err != nil {
		slog.Error("couldn't get public key", "error", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "there was an error signing out"})
		return
	}

	encKey := base64.RawURLEncoding.EncodeToString([]byte(pubKey))
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787

	// 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)
1788
	err = client.Disconnect(c, encKey)
1789
	if err != nil {
1790
1791
1792
		var authError api.AuthorizationError
		if errors.As(err, &authError) {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "you are not currently signed in"})
1793
1794
1795
1796
1797
1798
1799
1800
1801
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": "there was an error signing out"})
		return
	}

	c.JSON(http.StatusOK, nil)
}

1802
func (s *Server) PsHandler(c *gin.Context) {
1803
	models := []api.ProcessModelResponse{}
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814

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

1815
		mr := api.ProcessModelResponse{
1816
1817
			Model:     model.ShortName,
			Name:      model.ShortName,
Jesse Gross's avatar
Jesse Gross committed
1818
1819
			Size:      int64(v.totalSize),
			SizeVRAM:  int64(v.vramSize),
1820
1821
1822
1823
			Digest:    model.Digest,
			Details:   modelDetails,
			ExpiresAt: v.expiresAt,
		}
1824
		if v.Options != nil {
Jesse Gross's avatar
Jesse Gross committed
1825
			mr.ContextLength = v.Options.NumCtx
1826
		}
1827
1828
1829
1830
1831
1832
1833
1834
		// 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)
		}

1835
1836
1837
		models = append(models, mr)
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1838
1839
1840
1841
1842
	slices.SortStableFunc(models, func(i, j api.ProcessModelResponse) int {
		// longest duration remaining listed first
		return cmp.Compare(j.ExpiresAt.Unix(), i.ExpiresAt.Unix())
	})

1843
	c.JSON(http.StatusOK, api.ProcessResponse{Models: models})
1844
1845
}

Grace's avatar
Grace committed
1846
1847
1848
1849
1850
1851
1852
1853
1854
func toolCallId() string {
	const letterBytes = "abcdefghijklmnopqrstuvwxyz0123456789"
	b := make([]byte, 8)
	for i := range b {
		b[i] = letterBytes[rand.Intn(len(letterBytes))]
	}
	return "call_" + strings.ToLower(string(b))
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1855
func (s *Server) ChatHandler(c *gin.Context) {
1856
1857
	checkpointStart := time.Now()

Bruce MacDonald's avatar
Bruce MacDonald committed
1858
	var req api.ChatRequest
Michael Yang's avatar
Michael Yang committed
1859
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
Bruce MacDonald's avatar
Bruce MacDonald committed
1860
1861
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
Michael Yang's avatar
Michael Yang committed
1862
	} else if err != nil {
Bruce MacDonald's avatar
Bruce MacDonald committed
1863
1864
1865
1866
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

1867
1868
1869
1870
1871
	if req.TopLogprobs < 0 || req.TopLogprobs > 20 {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "top_logprobs must be between 0 and 20"})
		return
	}

1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
	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
1893
		}
1894
1895
1896
		return
	}

1897
1898
1899
1900
1901
	if req.TopLogprobs < 0 || req.TopLogprobs > 20 {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "top_logprobs must be between 0 and 20"})
		return
	}

1902
	// expire the runner
Michael Yang's avatar
Michael Yang committed
1903
	if len(req.Messages) == 0 && req.KeepAlive != nil && req.KeepAlive.Duration == 0 {
1904
		s.sched.expireRunner(m)
Patrick Devine's avatar
Patrick Devine committed
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915

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

1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
	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{}
		}

1936
1937
1938
1939
1940
1941
		var msgs []api.Message
		if len(req.Messages) > 0 {
			msgs = append(m.Messages, req.Messages...)
			if req.Messages[0].Role != "system" && m.System != "" {
				msgs = append([]api.Message{{Role: "system", Content: m.System}}, msgs...)
			}
1942
		}
1943

1944
1945
1946
1947
1948
1949
1950
1951
1952
		msgs = filterThinkTags(msgs, m)
		req.Messages = msgs

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

1953
1954
1955
1956
1957
1958
		contentType := "application/x-ndjson"
		if req.Stream != nil && !*req.Stream {
			contentType = "application/json; charset=utf-8"
		}
		c.Header("Content-Type", contentType)

1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
		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 {
1979
1980
1981
1982
1983
1984
			var authError api.AuthorizationError
			if errors.As(err, &authError) {
				sURL, sErr := signinURL()
				if sErr != nil {
					slog.Error(sErr.Error())
					c.JSON(http.StatusInternalServerError, gin.H{"error": "error getting authorization details"})
1985
1986
					return
				}
1987
1988
1989
1990
1991
1992
1993

				c.JSON(authError.StatusCode, gin.H{"error": "unauthorized", "signin_url": sURL})
				return
			}
			var apiError api.StatusError
			if errors.As(err, &apiError) {
				c.JSON(apiError.StatusCode, apiError)
1994
1995
				return
			}
1996
1997
1998
1999
2000
2001
2002
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		return
	}

2003
	caps := []model.Capability{model.CapabilityCompletion}
2004
	if len(req.Tools) > 0 {
2005
		caps = append(caps, model.CapabilityTools)
Michael Yang's avatar
tools  
Michael Yang committed
2006
	}
2007
2008

	modelCaps := m.Capabilities()
2009
	if slices.Contains(modelCaps, model.CapabilityThinking) {
2010
		caps = append(caps, model.CapabilityThinking)
2011
		if req.Think == nil {
2012
2013
			req.Think = &api.ThinkValue{Value: true}
		}
2014
2015
2016
2017
2018
	} else {
		if req.Think != nil && req.Think.Bool() {
			c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("%q does not support thinking", req.Model)})
			return
		}
2019
	}
Michael Yang's avatar
tools  
Michael Yang committed
2020

2021
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), caps, req.Options, req.KeepAlive)
Michael Yang's avatar
Michael Yang committed
2022
2023
	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
2024
		return
Michael Yang's avatar
Michael Yang committed
2025
	} else if err != nil {
Michael Yang's avatar
Michael Yang committed
2026
		handleScheduleError(c, req.Model, err)
Bruce MacDonald's avatar
Bruce MacDonald committed
2027
2028
		return
	}
Michael Yang's avatar
Michael Yang committed
2029

2030
2031
	checkpointLoaded := time.Now()

Michael Yang's avatar
Michael Yang committed
2032
2033
	if len(req.Messages) == 0 {
		c.JSON(http.StatusOK, api.ChatResponse{
2034
			Model:      req.Model,
Michael Yang's avatar
Michael Yang committed
2035
2036
			CreatedAt:  time.Now().UTC(),
			Message:    api.Message{Role: "assistant"},
2037
2038
			Done:       true,
			DoneReason: "load",
Michael Yang's avatar
Michael Yang committed
2039
		})
2040
2041
2042
		return
	}

Michael Yang's avatar
Michael Yang committed
2043
	msgs := append(m.Messages, req.Messages...)
2044
	if req.Messages[0].Role != "system" && m.System != "" {
Michael Yang's avatar
Michael Yang committed
2045
		msgs = append([]api.Message{{Role: "system", Content: m.System}}, msgs...)
2046
	}
2047
	msgs = filterThinkTags(msgs, m)
2048

2049
2050
	if shouldUseHarmony(m) && m.Config.Parser == "" {
		m.Config.Parser = "harmony"
Devon Rifkin's avatar
Devon Rifkin committed
2051
2052
	}

2053
	var builtinParser parsers.Parser
2054
	processedTools := req.Tools
2055

2056
2057
2058
2059
2060
2061
2062
2063
2064
	if m.Config.Parser != "" {
		builtinParser = parsers.ParserForName(m.Config.Parser)
		if builtinParser != nil {
			// Determine last message for chat prefill
			var lastMessage *api.Message
			if len(msgs) > 0 {
				lastMessage = &msgs[len(msgs)-1]
			}
			// Initialize parser and get processed tools
Grace's avatar
Grace committed
2065
			processedTools = builtinParser.Init(req.Tools, lastMessage, req.Think)
2066
2067
2068
		}
	}

2069
2070
	truncate := req.Truncate == nil || *req.Truncate
	prompt, images, err := chatPrompt(c.Request.Context(), m, r.Tokenize, opts, msgs, processedTools, req.Think, truncate)
Michael Yang's avatar
Michael Yang committed
2071
	if err != nil {
2072
		slog.Error("chat prompt error", "error", err)
Michael Yang's avatar
Michael Yang committed
2073
2074
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
2075
2076
	}

2077
2078
	// If debug mode is enabled, return the rendered template instead of calling the model
	if req.DebugRenderOnly {
Devon Rifkin's avatar
Devon Rifkin committed
2079
		c.JSON(http.StatusOK, api.ChatResponse{
2080
2081
			Model:     req.Model,
			CreatedAt: time.Now().UTC(),
Devon Rifkin's avatar
Devon Rifkin committed
2082
			DebugInfo: &api.DebugInfo{
2083
2084
2085
2086
2087
2088
2089
				RenderedTemplate: prompt,
				ImageCount:       len(images),
			},
		})
		return
	}

2090
2091
	// Validate Think value: string values currently only allowed for harmony/gptoss models
	if req.Think != nil && req.Think.IsString() && m.Config.Parser != "harmony" {
2092
		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
2093
2094
2095
		return
	}

2096
2097
	var thinkingState *thinking.Parser
	openingTag, closingTag := thinking.InferTags(m.Template.Template)
2098
	if req.Think != nil && req.Think.Bool() && openingTag != "" && closingTag != "" {
2099
		thinkingState = &thinking.Parser{
Devon Rifkin's avatar
Devon Rifkin committed
2100
2101
			OpeningTag: openingTag,
			ClosingTag: closingTag,
2102
		}
2103
2104
2105
2106

		if strings.HasSuffix(strings.TrimSpace(prompt), openingTag) {
			thinkingState.AddContent(openingTag)
		}
2107
2108
	}

2109
	var toolParser *tools.Parser
2110
	if len(req.Tools) > 0 && (builtinParser == nil || !builtinParser.HasToolSupport()) {
2111
		toolParser = tools.NewParser(m.Template.Template, req.Tools)
2112
2113
	}

2114
2115
2116
2117
2118
2119
2120
	type structuredOutputsState int
	const (
		structuredOutputsState_None structuredOutputsState = iota
		structuredOutputsState_ReadyToApply
		structuredOutputsState_Applying
	)

Bruce MacDonald's avatar
Bruce MacDonald committed
2121
2122
2123
	ch := make(chan any)
	go func() {
		defer close(ch)
2124

2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
		structuredOutputsState := structuredOutputsState_None

		for {
			var tb strings.Builder

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

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

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

2144
2145
2146
			// sets up new context given parent context per request
			ctx, cancel := context.WithCancel(c.Request.Context())
			err := r.Completion(ctx, llm.CompletionRequest{
2147
2148
2149
2150
2151
2152
2153
2154
				Prompt:      prompt,
				Images:      images,
				Format:      currentFormat,
				Options:     opts,
				Shift:       req.Shift == nil || *req.Shift,
				Truncate:    truncate,
				Logprobs:    req.Logprobs,
				TopLogprobs: req.TopLogprobs,
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
			}, func(r llm.CompletionResponse) {
				res := api.ChatResponse{
					Model:     req.Model,
					CreatedAt: time.Now().UTC(),
					Message:   api.Message{Role: "assistant", Content: r.Content},
					Done:      r.Done,
					Metrics: api.Metrics{
						PromptEvalCount:    r.PromptEvalCount,
						PromptEvalDuration: r.PromptEvalDuration,
						EvalCount:          r.EvalCount,
						EvalDuration:       r.EvalDuration,
					},
2167
					Logprobs: toAPILogprobs(r.Logprobs),
2168
				}
2169

2170
2171
2172
2173
2174
				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
2175

2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
				if builtinParser != nil {
					slog.Log(context.TODO(), logutil.LevelTrace, "builtin parser input", "parser", m.Config.Parser, "content", r.Content)

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

					res.Message.Content = content
					res.Message.Thinking = thinking
Grace's avatar
Grace committed
2187
2188
2189
					for i := range toolCalls {
						toolCalls[i].ID = toolCallId()
					}
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
					res.Message.ToolCalls = toolCalls

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

2200
					if res.Message.Content != "" || res.Message.Thinking != "" || len(res.Message.ToolCalls) > 0 || r.Done || len(res.Logprobs) > 0 {
2201
2202
2203
2204
2205
						slog.Log(context.TODO(), logutil.LevelTrace, "builtin parser output", "parser", m.Config.Parser, "content", content, "thinking", thinking, "toolCalls", toolCalls, "done", r.Done)
						ch <- res
					} else {
						slog.Log(context.TODO(), logutil.LevelTrace, "builtin parser empty output", "parser", m.Config.Parser)
					}
Devon Rifkin's avatar
Devon Rifkin committed
2206
2207
2208
					return
				}

2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
				if thinkingState != nil {
					thinkingContent, remainingContent := thinkingState.AddContent(res.Message.Content)
					if thinkingContent == "" && remainingContent == "" && !r.Done {
						// need to accumulate more to decide what to send
						return
					}
					res.Message.Thinking = thinkingContent
					tb.WriteString(thinkingContent)
					// emit the collected thinking text before restarting with structured outputs and clear unstructured content
					// to avoid leaking mixed tokens like "</think>Hello"
					if structuredOutputsState == structuredOutputsState_None && req.Format != nil && tb.String() != "" && remainingContent != "" {
						structuredOutputsState = structuredOutputsState_ReadyToApply
						res.Message.Content = ""
						ch <- res
						cancel()
						return
					}
					res.Message.Content = remainingContent
Devon Rifkin's avatar
Devon Rifkin committed
2227
2228
				}

2229
2230
2231
2232
2233
				if len(req.Tools) > 0 {
					toolCalls, content := toolParser.Add(res.Message.Content)
					if len(content) > 0 {
						res.Message.Content = content
					} else if len(toolCalls) > 0 {
Grace's avatar
Grace committed
2234
2235
2236
						for i := range toolCalls {
							toolCalls[i].ID = toolCallId()
						}
2237
2238
2239
						res.Message.ToolCalls = toolCalls
						res.Message.Content = ""
					} else if res.Message.Thinking != "" {
2240
						// don't return, fall through to send
2241
					} else {
2242
2243
2244
2245
2246
2247
2248
2249
						//  Send logprobs while content is being buffered by the parser for tool calls
						if len(res.Logprobs) > 0 && !r.Done {
							logprobRes := res
							logprobRes.Message.Content = ""
							logprobRes.Message.ToolCalls = nil
							ch <- logprobRes
						}

2250
2251
2252
2253
2254
2255
2256
						if r.Done {
							res.Message.Content = toolParser.Content()
							ch <- res
						}
						return
					}
				}
2257

2258
2259
2260
2261
2262
2263
				ch <- res
			})
			if err != nil {
				if structuredOutputsState == structuredOutputsState_ReadyToApply && strings.Contains(err.Error(), "context canceled") && c.Request.Context().Err() == nil {
					// only ignores error if it's a context cancellation due to setting structured outputs
				} else {
2264
2265
2266
2267
2268
2269
					var serr api.StatusError
					if errors.As(err, &serr) {
						ch <- gin.H{"error": serr.ErrorMessage, "status": serr.StatusCode}
					} else {
						ch <- gin.H{"error": err.Error()}
					}
2270
2271
2272
2273
					return
				}
			}

2274
2275
2276
2277
2278
2279
2280
2281
2282
			// ignored structured outputs cancellation falls through to here, start a new request with the structured outputs and updated prompt. use the
			if structuredOutputsState == structuredOutputsState_ReadyToApply {
				structuredOutputsState = structuredOutputsState_Applying
				msg := api.Message{
					Role:     "assistant",
					Thinking: tb.String(),
				}

				msgs = append(msgs, msg)
2283
				prompt, _, err = chatPrompt(c.Request.Context(), m, r.Tokenize, opts, msgs, processedTools, req.Think, truncate)
2284
2285
2286
				if err != nil {
					slog.Error("chat prompt error applying structured outputs", "error", err)
					ch <- gin.H{"error": err.Error()}
2287
					return
2288
				}
2289
2290
2291
2292
2293
2294
2295
2296
				// force constraining by terminating thinking header, the parser is already at this state
				// when the last message is thinking, the rendered for gpt-oss cannot disambiguate between having the
				// model continue thinking or ending thinking and outputting the final message.
				// TODO(parthsareen): consider adding prefill disambiguation logic to the renderer for structured outputs.
				if shouldUseHarmony(m) || (builtinParser != nil && m.Config.Parser == "harmony") {
					prompt += "<|end|><|start|>assistant<|channel|>final<|message|>"
				}
				continue
2297
			}
2298

2299
			break
Bruce MacDonald's avatar
Bruce MacDonald committed
2300
2301
2302
2303
		}
	}()

	if req.Stream != nil && !*req.Stream {
Michael Yang's avatar
tools  
Michael Yang committed
2304
		var resp api.ChatResponse
2305
		var toolCalls []api.ToolCall
2306
		var allLogprobs []api.Logprob
2307
2308
		var sbThinking strings.Builder
		var sbContent strings.Builder
Michael Yang's avatar
Michael Yang committed
2309
2310
		for rr := range ch {
			switch t := rr.(type) {
2311
			case api.ChatResponse:
2312
2313
				sbThinking.WriteString(t.Message.Thinking)
				sbContent.WriteString(t.Message.Content)
Michael Yang's avatar
tools  
Michael Yang committed
2314
				resp = t
2315
2316
2317
				if len(req.Tools) > 0 {
					toolCalls = append(toolCalls, t.Message.ToolCalls...)
				}
2318
2319
2320
2321
				// Accumulate logprobs from all chunks for non-streaming response
				if len(t.Logprobs) > 0 {
					allLogprobs = append(allLogprobs, t.Logprobs...)
				}
2322
2323
2324
2325
2326
2327
			case gin.H:
				msg, ok := t["error"].(string)
				if !ok {
					msg = "unexpected error format in response"
				}

2328
2329
2330
2331
2332
2333
				status, ok := t["status"].(int)
				if !ok {
					status = http.StatusInternalServerError
				}

				c.JSON(status, gin.H{"error": msg})
Michael Yang's avatar
Michael Yang committed
2334
				return
2335
			default:
Michael Yang's avatar
Michael Yang committed
2336
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
2337
				return
Bruce MacDonald's avatar
Bruce MacDonald committed
2338
2339
			}
		}
2340

2341
2342
		resp.Message.Content = sbContent.String()
		resp.Message.Thinking = sbThinking.String()
2343
		resp.Logprobs = allLogprobs
2344

2345
2346
		if len(toolCalls) > 0 {
			resp.Message.ToolCalls = toolCalls
Michael Yang's avatar
tools  
Michael Yang committed
2347
2348
2349
		}

		c.JSON(http.StatusOK, resp)
Bruce MacDonald's avatar
Bruce MacDonald committed
2350
2351
2352
2353
2354
		return
	}

	streamResponse(c, ch)
}
2355

Michael Yang's avatar
Michael Yang committed
2356
func handleScheduleError(c *gin.Context, name string, err error) {
Michael Yang's avatar
Michael Yang committed
2357
	switch {
2358
	case errors.Is(err, errCapabilities), errors.Is(err, errRequired):
Michael Yang's avatar
Michael Yang committed
2359
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
2360
	case errors.Is(err, context.Canceled):
2361
		c.JSON(499, gin.H{"error": "request canceled"})
Michael Yang's avatar
Michael Yang committed
2362
	case errors.Is(err, ErrMaxQueue):
2363
		c.JSON(http.StatusServiceUnavailable, gin.H{"error": err.Error()})
Michael Yang's avatar
Michael Yang committed
2364
2365
	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
2366
2367
	default:
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
2368
2369
	}
}
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381

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 {
2382
2383
2384
2385
2386
				// 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.
2387
				thinkingState := &thinking.Parser{
Devon Rifkin's avatar
Devon Rifkin committed
2388
2389
					OpeningTag: "<think>",
					ClosingTag: "</think>",
2390
				}
Devon Rifkin's avatar
Devon Rifkin committed
2391
				_, content := thinkingState.AddContent(msg.Content)
2392
				msgs[i].Content = content
2393
2394
2395
2396
2397
			}
		}
	}
	return msgs
}
2398