routes.go 35.6 KB
Newer Older
mashun1's avatar
v1  
mashun1 committed
1
2
3
package server

import (
xuxzh1's avatar
init  
xuxzh1 committed
4
	"bytes"
mashun1's avatar
v1  
mashun1 committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
	"cmp"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"math"
	"net"
	"net/http"
	"net/netip"
	"os"
	"os/signal"
	"path/filepath"
xuxzh1's avatar
init  
xuxzh1 committed
19
	"slices"
mashun1's avatar
v1  
mashun1 committed
20
21
22
23
24
25
	"strings"
	"syscall"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
xuxzh1's avatar
init  
xuxzh1 committed
26
	"golang.org/x/sync/errgroup"
mashun1's avatar
v1  
mashun1 committed
27
28
29
30
31
32
33

	"github.com/ollama/ollama/api"
	"github.com/ollama/ollama/envconfig"
	"github.com/ollama/ollama/gpu"
	"github.com/ollama/ollama/llm"
	"github.com/ollama/ollama/openai"
	"github.com/ollama/ollama/parser"
xuxzh1's avatar
init  
xuxzh1 committed
34
	"github.com/ollama/ollama/template"
mashun1's avatar
v1  
mashun1 committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
	"github.com/ollama/ollama/types/errtypes"
	"github.com/ollama/ollama/types/model"
	"github.com/ollama/ollama/version"
)

var mode string = gin.DebugMode

type Server struct {
	addr  net.Addr
	sched *Scheduler
}

func init() {
	switch mode {
	case gin.DebugMode:
	case gin.ReleaseMode:
	case gin.TestMode:
	default:
		mode = gin.DebugMode
	}

	gin.SetMode(mode)
}

xuxzh1's avatar
init  
xuxzh1 committed
59
60
61
62
var (
	errRequired    = errors.New("is required")
	errBadTemplate = errors.New("template error")
)
mashun1's avatar
v1  
mashun1 committed
63
64
65
66
67
68
69
70
71
72
73
74
75
76

func modelOptions(model *Model, requestOpts map[string]interface{}) (api.Options, error) {
	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
}

xuxzh1's avatar
init  
xuxzh1 committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// 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.
func (s *Server) scheduleRunner(ctx context.Context, name string, caps []Capability, requestOpts map[string]any, keepAlive *api.Duration) (llm.LlamaServer, *Model, *api.Options, error) {
	if name == "" {
		return nil, nil, nil, fmt.Errorf("model %w", errRequired)
	}

	model, err := GetModel(name)
	if err != nil {
		return nil, nil, nil, err
	}

	if err := model.CheckCapabilities(caps...); err != nil {
		return nil, nil, nil, fmt.Errorf("%s %w", name, err)
	}

	opts, err := modelOptions(model, requestOpts)
	if err != nil {
		return nil, nil, nil, err
	}

	runnerCh, errCh := s.sched.GetRunner(ctx, model, opts, keepAlive)
	var runner *runnerRef
	select {
	case runner = <-runnerCh:
	case err = <-errCh:
		return nil, nil, nil, err
	}

	return runner.llama, model, &opts, nil
mashun1's avatar
v1  
mashun1 committed
107
108
109
110
111
}

func (s *Server) GenerateHandler(c *gin.Context) {
	checkpointStart := time.Now()
	var req api.GenerateRequest
xuxzh1's avatar
init  
xuxzh1 committed
112
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
mashun1's avatar
v1  
mashun1 committed
113
114
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
xuxzh1's avatar
init  
xuxzh1 committed
115
	} else if err != nil {
mashun1's avatar
v1  
mashun1 committed
116
117
118
119
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

xuxzh1's avatar
init  
xuxzh1 committed
120
121
	if req.Format != "" && req.Format != "json" {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be empty or \"json\""})
mashun1's avatar
v1  
mashun1 committed
122
		return
xuxzh1's avatar
init  
xuxzh1 committed
123
	} else if req.Raw && (req.Template != "" || req.System != "" || len(req.Context) > 0) {
mashun1's avatar
v1  
mashun1 committed
124
125
126
127
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "raw mode does not support template, system, or context"})
		return
	}

xuxzh1's avatar
init  
xuxzh1 committed
128
129
130
	caps := []Capability{CapabilityCompletion}
	if req.Suffix != "" {
		caps = append(caps, CapabilityInsert)
mashun1's avatar
v1  
mashun1 committed
131
132
	}

xuxzh1's avatar
init  
xuxzh1 committed
133
134
135
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), req.Model, caps, req.Options, req.KeepAlive)
	if errors.Is(err, errCapabilityCompletion) {
		c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("%q does not support generate", req.Model)})
mashun1's avatar
v1  
mashun1 committed
136
		return
xuxzh1's avatar
init  
xuxzh1 committed
137
138
	} else if err != nil {
		handleScheduleError(c, req.Model, err)
mashun1's avatar
v1  
mashun1 committed
139
140
141
		return
	}

xuxzh1's avatar
init  
xuxzh1 committed
142
	checkpointLoaded := time.Now()
mashun1's avatar
v1  
mashun1 committed
143

xuxzh1's avatar
init  
xuxzh1 committed
144
	if req.Prompt == "" {
mashun1's avatar
v1  
mashun1 committed
145
146
		c.JSON(http.StatusOK, api.GenerateResponse{
			Model:      req.Model,
xuxzh1's avatar
init  
xuxzh1 committed
147
			CreatedAt:  time.Now().UTC(),
mashun1's avatar
v1  
mashun1 committed
148
149
150
151
152
153
			Done:       true,
			DoneReason: "load",
		})
		return
	}

xuxzh1's avatar
init  
xuxzh1 committed
154
155
156
157
	images := make([]llm.ImageData, len(req.Images))
	for i := range req.Images {
		images[i] = llm.ImageData{ID: i, Data: req.Images[i]}
	}
mashun1's avatar
v1  
mashun1 committed
158

xuxzh1's avatar
init  
xuxzh1 committed
159
160
161
162
163
164
165
166
167
	prompt := req.Prompt
	if !req.Raw {
		tmpl := m.Template
		if req.Template != "" {
			tmpl, err = template.Parse(req.Template)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
mashun1's avatar
v1  
mashun1 committed
168
169
		}

xuxzh1's avatar
init  
xuxzh1 committed
170
171
172
173
174
175
176
177
178
179
180
		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})
			}
mashun1's avatar
v1  
mashun1 committed
181

xuxzh1's avatar
init  
xuxzh1 committed
182
183
184
			if req.Context == nil {
				msgs = append(msgs, m.Messages...)
			}
mashun1's avatar
v1  
mashun1 committed
185

xuxzh1's avatar
init  
xuxzh1 committed
186
187
188
			for _, i := range images {
				msgs = append(msgs, api.Message{Role: "user", Content: fmt.Sprintf("[img-%d]", i.ID)})
			}
mashun1's avatar
v1  
mashun1 committed
189

xuxzh1's avatar
init  
xuxzh1 committed
190
			values.Messages = append(msgs, api.Message{Role: "user", Content: req.Prompt})
mashun1's avatar
v1  
mashun1 committed
191
192
		}

xuxzh1's avatar
init  
xuxzh1 committed
193
		var b bytes.Buffer
mashun1's avatar
v1  
mashun1 committed
194
		if req.Context != nil {
xuxzh1's avatar
init  
xuxzh1 committed
195
			s, err := r.Detokenize(c.Request.Context(), req.Context)
mashun1's avatar
v1  
mashun1 committed
196
197
198
199
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
xuxzh1's avatar
init  
xuxzh1 committed
200
			b.WriteString(s)
mashun1's avatar
v1  
mashun1 committed
201
202
		}

xuxzh1's avatar
init  
xuxzh1 committed
203
204
205
206
		if err := tmpl.Execute(&b, values); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
mashun1's avatar
v1  
mashun1 committed
207

xuxzh1's avatar
init  
xuxzh1 committed
208
		prompt = b.String()
mashun1's avatar
v1  
mashun1 committed
209
210
	}

xuxzh1's avatar
init  
xuxzh1 committed
211
	slog.Debug("generate request", "prompt", prompt, "images", images)
mashun1's avatar
v1  
mashun1 committed
212
213
214

	ch := make(chan any)
	go func() {
xuxzh1's avatar
init  
xuxzh1 committed
215
216
		// TODO (jmorganca): avoid building the response twice both here and below
		var sb strings.Builder
mashun1's avatar
v1  
mashun1 committed
217
		defer close(ch)
xuxzh1's avatar
init  
xuxzh1 committed
218
219
220
221
222
223
224
		if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
			Prompt:  prompt,
			Images:  images,
			Format:  req.Format,
			Options: opts,
		}, func(cr llm.CompletionResponse) {
			res := api.GenerateResponse{
mashun1's avatar
v1  
mashun1 committed
225
226
				Model:      req.Model,
				CreatedAt:  time.Now().UTC(),
xuxzh1's avatar
init  
xuxzh1 committed
227
228
229
				Response:   cr.Content,
				Done:       cr.Done,
				DoneReason: cr.DoneReason,
mashun1's avatar
v1  
mashun1 committed
230
				Metrics: api.Metrics{
xuxzh1's avatar
init  
xuxzh1 committed
231
232
233
234
					PromptEvalCount:    cr.PromptEvalCount,
					PromptEvalDuration: cr.PromptEvalDuration,
					EvalCount:          cr.EvalCount,
					EvalDuration:       cr.EvalDuration,
mashun1's avatar
v1  
mashun1 committed
235
236
237
				},
			}

xuxzh1's avatar
init  
xuxzh1 committed
238
239
240
			if _, err := sb.WriteString(cr.Content); err != nil {
				ch <- gin.H{"error": err.Error()}
			}
mashun1's avatar
v1  
mashun1 committed
241

xuxzh1's avatar
init  
xuxzh1 committed
242
243
244
			if cr.Done {
				res.TotalDuration = time.Since(checkpointStart)
				res.LoadDuration = checkpointLoaded.Sub(checkpointStart)
mashun1's avatar
v1  
mashun1 committed
245

xuxzh1's avatar
init  
xuxzh1 committed
246
247
				if !req.Raw {
					tokens, err := r.Tokenize(c.Request.Context(), prompt+sb.String())
mashun1's avatar
v1  
mashun1 committed
248
249
250
251
					if err != nil {
						ch <- gin.H{"error": err.Error()}
						return
					}
xuxzh1's avatar
init  
xuxzh1 committed
252
					res.Context = tokens
mashun1's avatar
v1  
mashun1 committed
253
254
255
				}
			}

xuxzh1's avatar
init  
xuxzh1 committed
256
257
			ch <- res
		}); err != nil {
mashun1's avatar
v1  
mashun1 committed
258
259
260
261
262
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
xuxzh1's avatar
init  
xuxzh1 committed
263
		var r api.GenerateResponse
mashun1's avatar
v1  
mashun1 committed
264
		var sb strings.Builder
xuxzh1's avatar
init  
xuxzh1 committed
265
266
		for rr := range ch {
			switch t := rr.(type) {
mashun1's avatar
v1  
mashun1 committed
267
			case api.GenerateResponse:
xuxzh1's avatar
init  
xuxzh1 committed
268
269
				sb.WriteString(t.Response)
				r = t
mashun1's avatar
v1  
mashun1 committed
270
			case gin.H:
xuxzh1's avatar
init  
xuxzh1 committed
271
272
273
				msg, ok := t["error"].(string)
				if !ok {
					msg = "unexpected error format in response"
mashun1's avatar
v1  
mashun1 committed
274
				}
xuxzh1's avatar
init  
xuxzh1 committed
275
276
277

				c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
				return
mashun1's avatar
v1  
mashun1 committed
278
			default:
xuxzh1's avatar
init  
xuxzh1 committed
279
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
mashun1's avatar
v1  
mashun1 committed
280
281
282
283
				return
			}
		}

xuxzh1's avatar
init  
xuxzh1 committed
284
285
		r.Response = sb.String()
		c.JSON(http.StatusOK, r)
mashun1's avatar
v1  
mashun1 committed
286
287
288
289
290
291
		return
	}

	streamResponse(c, ch)
}

xuxzh1's avatar
init  
xuxzh1 committed
292
293
294
func (s *Server) EmbedHandler(c *gin.Context) {
	checkpointStart := time.Now()
	var req api.EmbedRequest
mashun1's avatar
v1  
mashun1 committed
295
296
297
298
299
300
301
302
303
304
	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
	}

xuxzh1's avatar
init  
xuxzh1 committed
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
	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:
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid input type"})
mashun1's avatar
v1  
mashun1 committed
328
329
330
		return
	}

xuxzh1's avatar
init  
xuxzh1 committed
331
332
333
334
335
336
	if len(input) == 0 {
		c.JSON(http.StatusOK, api.EmbedResponse{Model: req.Model, Embeddings: [][]float32{}})
		return
	}

	r, m, opts, err := s.scheduleRunner(c.Request.Context(), req.Model, []Capability{}, req.Options, req.KeepAlive)
mashun1's avatar
v1  
mashun1 committed
337
	if err != nil {
xuxzh1's avatar
init  
xuxzh1 committed
338
		handleScheduleError(c, req.Model, err)
mashun1's avatar
v1  
mashun1 committed
339
340
341
		return
	}

xuxzh1's avatar
init  
xuxzh1 committed
342
343
344
	checkpointLoaded := time.Now()

	kvData, err := getKVData(m.ModelPath, false)
mashun1's avatar
v1  
mashun1 committed
345
346
347
348
349
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

xuxzh1's avatar
init  
xuxzh1 committed
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
	var count int
	for i, s := range input {
		tokens, err := r.Tokenize(c.Request.Context(), s)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

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

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

		count += len(tokens)

		input[i] = s
mashun1's avatar
v1  
mashun1 committed
376
377
	}

xuxzh1's avatar
init  
xuxzh1 committed
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
	var g errgroup.Group
	embeddings := make([][]float32, len(input))
	for i, text := range input {
		g.Go(func() error {
			embedding, err := r.Embedding(c.Request.Context(), text)
			if err != nil {
				return err
			}
			embeddings[i] = normalize(embedding)
			return nil
		})
	}

	if err := g.Wait(); err != nil {
		slog.Error("embedding generation failed", "error", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Errorf("failed to generate embeddings: %v", err)})
		return
	}

	resp := api.EmbedResponse{
		Model:           req.Model,
		Embeddings:      embeddings,
		TotalDuration:   time.Since(checkpointStart),
		LoadDuration:    checkpointLoaded.Sub(checkpointStart),
		PromptEvalCount: count,
	}
	c.JSON(http.StatusOK, resp)
}

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

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

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

func (s *Server) EmbeddingsHandler(c *gin.Context) {
	var req api.EmbeddingRequest
	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()})
		return
	}

	r, _, _, err := s.scheduleRunner(c.Request.Context(), req.Model, []Capability{}, req.Options, req.KeepAlive)
	if err != nil {
		handleScheduleError(c, req.Model, err)
mashun1's avatar
v1  
mashun1 committed
437
438
439
440
441
442
443
444
445
		return
	}

	// an empty request loads the model
	if req.Prompt == "" {
		c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: []float64{}})
		return
	}

xuxzh1's avatar
init  
xuxzh1 committed
446
	embedding, err := r.Embedding(c.Request.Context(), req.Prompt)
mashun1's avatar
v1  
mashun1 committed
447
448
449
450
451
452
	if err != nil {
		slog.Info(fmt.Sprintf("embedding generation failed: %v", err))
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
		return
	}

xuxzh1's avatar
init  
xuxzh1 committed
453
454
455
456
457
	var e []float64
	for _, v := range embedding {
		e = append(e, float64(v))
	}

mashun1's avatar
v1  
mashun1 committed
458
	resp := api.EmbeddingResponse{
xuxzh1's avatar
init  
xuxzh1 committed
459
		Embedding: e,
mashun1's avatar
v1  
mashun1 committed
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
	}
	c.JSON(http.StatusOK, resp)
}

func (s *Server) PullModelHandler(c *gin.Context) {
	var req api.PullRequest
	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
	}

	name := model.ParseName(cmp.Or(req.Model, req.Name))
	if !name.IsValid() {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid model name"})
		return
	}

	if err := checkNameExists(name); err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	ch := make(chan any)
	go func() {
		defer close(ch)
		fn := func(r api.ProgressResponse) {
			ch <- r
		}

		regOpts := &registryOptions{
			Insecure: req.Insecure,
		}

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

		if err := PullModel(ctx, name.DisplayShortest(), regOpts, fn); err != nil {
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

	streamResponse(c, ch)
}

func (s *Server) PushModelHandler(c *gin.Context) {
	var req api.PushRequest
	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 model string
	if req.Model != "" {
		model = req.Model
	} else if req.Name != "" {
		model = req.Name
	} else {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
	}

	ch := make(chan any)
	go func() {
		defer close(ch)
		fn := func(r api.ProgressResponse) {
			ch <- r
		}

		regOpts := &registryOptions{
			Insecure: req.Insecure,
		}

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

		if err := PushModel(ctx, model, regOpts, fn); err != nil {
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
		waitForStream(c, ch)
		return
	}

	streamResponse(c, ch)
}

func checkNameExists(name model.Name) error {
	names, err := Manifests()
	if err != nil {
		return err
	}

	for n := range names {
		if strings.EqualFold(n.Filepath(), name.Filepath()) && n != name {
xuxzh1's avatar
init  
xuxzh1 committed
571
			return errors.New("a model with that name already exists")
mashun1's avatar
v1  
mashun1 committed
572
573
574
575
576
577
578
		}
	}

	return nil
}

func (s *Server) CreateModelHandler(c *gin.Context) {
xuxzh1's avatar
init  
xuxzh1 committed
579
580
	var r api.CreateRequest
	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
mashun1's avatar
v1  
mashun1 committed
581
582
583
584
585
586
587
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
	} else if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

xuxzh1's avatar
init  
xuxzh1 committed
588
	name := model.ParseName(cmp.Or(r.Model, r.Name))
mashun1's avatar
v1  
mashun1 committed
589
590
591
592
593
594
595
596
597
598
	if !name.IsValid() {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": errtypes.InvalidModelNameErrMsg})
		return
	}

	if err := checkNameExists(name); err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

xuxzh1's avatar
init  
xuxzh1 committed
599
	if r.Path == "" && r.Modelfile == "" {
mashun1's avatar
v1  
mashun1 committed
600
601
602
603
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
		return
	}

xuxzh1's avatar
init  
xuxzh1 committed
604
605
606
	var sr io.Reader = strings.NewReader(r.Modelfile)
	if r.Path != "" && r.Modelfile == "" {
		f, err := os.Open(r.Path)
mashun1's avatar
v1  
mashun1 committed
607
608
609
610
611
612
		if err != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
			return
		}
		defer f.Close()

xuxzh1's avatar
init  
xuxzh1 committed
613
		sr = f
mashun1's avatar
v1  
mashun1 committed
614
615
	}

xuxzh1's avatar
init  
xuxzh1 committed
616
	f, err := parser.ParseFile(sr)
mashun1's avatar
v1  
mashun1 committed
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	ch := make(chan any)
	go func() {
		defer close(ch)
		fn := func(resp api.ProgressResponse) {
			ch <- resp
		}

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

xuxzh1's avatar
init  
xuxzh1 committed
632
633
634
635
		quantization := cmp.Or(r.Quantize, r.Quantization)
		if err := CreateModel(ctx, name, filepath.Dir(r.Path), strings.ToUpper(quantization), f, fn); errors.Is(err, errBadTemplate) {
			ch <- gin.H{"error": err.Error(), "status": http.StatusBadRequest}
		} else if err != nil {
mashun1's avatar
v1  
mashun1 committed
636
637
638
639
			ch <- gin.H{"error": err.Error()}
		}
	}()

xuxzh1's avatar
init  
xuxzh1 committed
640
	if r.Stream != nil && !*r.Stream {
mashun1's avatar
v1  
mashun1 committed
641
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
669
670
671
672
673
		waitForStream(c, ch)
		return
	}

	streamResponse(c, ch)
}

func (s *Server) DeleteModelHandler(c *gin.Context) {
	var r api.DeleteRequest
	if err := c.ShouldBindJSON(&r); 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()})
		return
	}

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

	m, err := ParseNamedManifest(n)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if err := m.Remove(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
xuxzh1's avatar
init  
xuxzh1 committed
674
675
676
677
678

	if err := m.RemoveLayers(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
mashun1's avatar
v1  
mashun1 committed
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
}

func (s *Server) ShowModelHandler(c *gin.Context) {
	var req api.ShowRequest
	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
	}

	if req.Model != "" {
		// noop
	} else if req.Name != "" {
		req.Model = req.Name
	} else {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
		return
	}

	resp, err := GetModelInfo(req)
	if err != nil {
xuxzh1's avatar
init  
xuxzh1 committed
704
705
		switch {
		case os.IsNotExist(err):
mashun1's avatar
v1  
mashun1 committed
706
			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
xuxzh1's avatar
init  
xuxzh1 committed
707
708
709
		case err.Error() == "invalid model name":
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		default:
mashun1's avatar
v1  
mashun1 committed
710
711
712
713
714
715
716
717
718
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
		return
	}

	c.JSON(http.StatusOK, resp)
}

func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
xuxzh1's avatar
init  
xuxzh1 committed
719
	m, err := GetModel(req.Model)
mashun1's avatar
v1  
mashun1 committed
720
721
722
723
724
	if err != nil {
		return nil, err
	}

	modelDetails := api.ModelDetails{
xuxzh1's avatar
init  
xuxzh1 committed
725
726
727
728
729
730
		ParentModel:       m.ParentModel,
		Format:            m.Config.ModelFormat,
		Family:            m.Config.ModelFamily,
		Families:          m.Config.ModelFamilies,
		ParameterSize:     m.Config.ModelType,
		QuantizationLevel: m.Config.FileType,
mashun1's avatar
v1  
mashun1 committed
731
732
733
	}

	if req.System != "" {
xuxzh1's avatar
init  
xuxzh1 committed
734
		m.System = req.System
mashun1's avatar
v1  
mashun1 committed
735
736
	}

xuxzh1's avatar
init  
xuxzh1 committed
737
738
739
	msgs := make([]api.Message, len(m.Messages))
	for i, msg := range m.Messages {
		msgs[i] = api.Message{Role: msg.Role, Content: msg.Content}
mashun1's avatar
v1  
mashun1 committed
740
741
	}

xuxzh1's avatar
init  
xuxzh1 committed
742
743
744
745
746
747
748
749
	n := model.ParseName(req.Model)
	if !n.IsValid() {
		return nil, errors.New("invalid model name")
	}

	manifest, err := ParseNamedManifest(n)
	if err != nil {
		return nil, err
mashun1's avatar
v1  
mashun1 committed
750
751
752
	}

	resp := &api.ShowResponse{
xuxzh1's avatar
init  
xuxzh1 committed
753
754
755
756
757
758
		License:    strings.Join(m.License, "\n"),
		System:     m.System,
		Template:   m.Template.String(),
		Details:    modelDetails,
		Messages:   msgs,
		ModifiedAt: manifest.fi.ModTime(),
mashun1's avatar
v1  
mashun1 committed
759
760
761
762
	}

	var params []string
	cs := 30
xuxzh1's avatar
init  
xuxzh1 committed
763
	for k, v := range m.Options {
mashun1's avatar
v1  
mashun1 committed
764
765
766
767
768
769
770
771
772
773
774
775
776
		switch val := v.(type) {
		case []interface{}:
			for _, nv := range val {
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
			}
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
		}
	}
	resp.Parameters = strings.Join(params, "\n")

	for k, v := range req.Options {
		if _, ok := req.Options[k]; ok {
xuxzh1's avatar
init  
xuxzh1 committed
777
			m.Options[k] = v
mashun1's avatar
v1  
mashun1 committed
778
779
780
781
782
783
		}
	}

	var sb strings.Builder
	fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"")
	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
xuxzh1's avatar
init  
xuxzh1 committed
784
785
	fmt.Fprintf(&sb, "# FROM %s\n\n", m.ShortName)
	fmt.Fprint(&sb, m.String())
mashun1's avatar
v1  
mashun1 committed
786
787
	resp.Modelfile = sb.String()

xuxzh1's avatar
init  
xuxzh1 committed
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
	kvData, err := getKVData(m.ModelPath, req.Verbose)
	if err != nil {
		return nil, err
	}
	delete(kvData, "general.name")
	delete(kvData, "tokenizer.chat_template")
	resp.ModelInfo = kvData

	if len(m.ProjectorPaths) > 0 {
		projectorData, err := getKVData(m.ProjectorPaths[0], req.Verbose)
		if err != nil {
			return nil, err
		}
		resp.ProjectorInfo = projectorData
	}

mashun1's avatar
v1  
mashun1 committed
804
805
806
	return resp, nil
}

xuxzh1's avatar
init  
xuxzh1 committed
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
func getKVData(digest string, verbose bool) (llm.KV, error) {
	maxArraySize := 0
	if verbose {
		maxArraySize = -1
	}
	kvData, err := llm.LoadModel(digest, maxArraySize)
	if err != nil {
		return nil, err
	}

	kv := kvData.KV()

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

	return kv, nil
}

mashun1's avatar
v1  
mashun1 committed
830
831
832
833
834
835
836
func (s *Server) ListModelsHandler(c *gin.Context) {
	ms, err := Manifests()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

xuxzh1's avatar
init  
xuxzh1 committed
837
	models := []api.ListModelResponse{}
mashun1's avatar
v1  
mashun1 committed
838
839
	for n, m := range ms {
		var cf ConfigV2
xuxzh1's avatar
init  
xuxzh1 committed
840
841
842
843
844
845
846
847
848
849
850
851
852

		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
			}
mashun1's avatar
v1  
mashun1 committed
853
854
855
		}

		// tag should never be masked
xuxzh1's avatar
init  
xuxzh1 committed
856
		models = append(models, api.ListModelResponse{
mashun1's avatar
v1  
mashun1 committed
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
			Model:      n.DisplayShortest(),
			Name:       n.DisplayShortest(),
			Size:       m.Size(),
			Digest:     m.digest,
			ModifiedAt: m.fi.ModTime(),
			Details: api.ModelDetails{
				Format:            cf.ModelFormat,
				Family:            cf.ModelFamily,
				Families:          cf.ModelFamilies,
				ParameterSize:     cf.ModelType,
				QuantizationLevel: cf.FileType,
			},
		})
	}

xuxzh1's avatar
init  
xuxzh1 committed
872
	slices.SortStableFunc(models, func(i, j api.ListModelResponse) int {
mashun1's avatar
v1  
mashun1 committed
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
		// most recently modified first
		return cmp.Compare(j.ModifiedAt.Unix(), i.ModifiedAt.Unix())
	})

	c.JSON(http.StatusOK, api.ListResponse{Models: models})
}

func (s *Server) CopyModelHandler(c *gin.Context) {
	var r api.CopyRequest
	if err := c.ShouldBindJSON(&r); 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()})
		return
	}

	src := model.ParseName(r.Source)
	if !src.IsValid() {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("source %q is invalid", r.Source)})
		return
	}

	dst := model.ParseName(r.Destination)
	if !dst.IsValid() {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("destination %q is invalid", r.Destination)})
		return
	}

	if err := checkNameExists(dst); err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

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

func (s *Server) HeadBlobHandler(c *gin.Context) {
	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
	}

	c.Status(http.StatusOK)
}

func (s *Server) CreateBlobHandler(c *gin.Context) {
	if ib, ok := intermediateBlobs[c.Param("digest")]; ok {
		p, err := GetBlobsPath(ib)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		if _, err := os.Stat(p); errors.Is(err, os.ErrNotExist) {
			slog.Info("evicting intermediate blob which no longer exists", "digest", ib)
			delete(intermediateBlobs, c.Param("digest"))
		} else if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		} else {
			c.Status(http.StatusOK)
			return
		}
	}

	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
	}

	layer, err := NewLayer(c.Request.Body, "")
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

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

	c.Status(http.StatusCreated)
}

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
}

func allowedHost(host string) bool {
	if host == "" || host == "localhost" {
		return true
	}

	if hostname, err := os.Hostname(); err == nil && host == hostname {
		return true
	}

xuxzh1's avatar
init  
xuxzh1 committed
1011
	tlds := []string{
mashun1's avatar
v1  
mashun1 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
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
		"localhost",
		"local",
		"internal",
	}

	// check if the host is a local TLD
	for _, tld := range tlds {
		if strings.HasSuffix(host, "."+tld) {
			return true
		}
	}

	return false
}

func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
	return func(c *gin.Context) {
		if addr == nil {
			c.Next()
			return
		}

		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
			c.Next()
			return
		}

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

		if addr, err := netip.ParseAddr(host); err == nil {
			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
				c.Next()
				return
			}
		}

		if allowedHost(host) {
xuxzh1's avatar
init  
xuxzh1 committed
1052
			if c.Request.Method == http.MethodOptions {
mashun1's avatar
v1  
mashun1 committed
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
				c.AbortWithStatus(http.StatusNoContent)
				return
			}

			c.Next()
			return
		}

		c.AbortWithStatus(http.StatusForbidden)
	}
}

func (s *Server) GenerateRoutes() http.Handler {
	config := cors.DefaultConfig()
	config.AllowWildcard = true
	config.AllowBrowserExtensions = true
	config.AllowHeaders = []string{"Authorization", "Content-Type", "User-Agent", "Accept", "X-Requested-With"}
xuxzh1's avatar
init  
xuxzh1 committed
1070
1071
1072
1073
1074
	openAIProperties := []string{"lang", "package-version", "os", "arch", "runtime", "runtime-version", "async"}
	for _, prop := range openAIProperties {
		config.AllowHeaders = append(config.AllowHeaders, "x-stainless-"+prop)
	}
	config.AllowOrigins = envconfig.Origins()
mashun1's avatar
v1  
mashun1 committed
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084

	r := gin.Default()
	r.Use(
		cors.New(config),
		allowedHostsMiddleware(s.addr),
	)

	r.POST("/api/pull", s.PullModelHandler)
	r.POST("/api/generate", s.GenerateHandler)
	r.POST("/api/chat", s.ChatHandler)
xuxzh1's avatar
init  
xuxzh1 committed
1085
	r.POST("/api/embed", s.EmbedHandler)
mashun1's avatar
v1  
mashun1 committed
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
	r.POST("/api/embeddings", s.EmbeddingsHandler)
	r.POST("/api/create", s.CreateModelHandler)
	r.POST("/api/push", s.PushModelHandler)
	r.POST("/api/copy", s.CopyModelHandler)
	r.DELETE("/api/delete", s.DeleteModelHandler)
	r.POST("/api/show", s.ShowModelHandler)
	r.POST("/api/blobs/:digest", s.CreateBlobHandler)
	r.HEAD("/api/blobs/:digest", s.HeadBlobHandler)
	r.GET("/api/ps", s.ProcessHandler)

	// Compatibility endpoints
xuxzh1's avatar
init  
xuxzh1 committed
1097
1098
1099
1100
1101
	r.POST("/v1/chat/completions", openai.ChatMiddleware(), s.ChatHandler)
	r.POST("/v1/completions", openai.CompletionsMiddleware(), s.GenerateHandler)
	r.POST("/v1/embeddings", openai.EmbeddingsMiddleware(), s.EmbedHandler)
	r.GET("/v1/models", openai.ListMiddleware(), s.ListModelsHandler)
	r.GET("/v1/models/:model", openai.RetrieveMiddleware(), s.ShowModelHandler)
mashun1's avatar
v1  
mashun1 committed
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118

	for _, method := range []string{http.MethodGet, http.MethodHead} {
		r.Handle(method, "/", func(c *gin.Context) {
			c.String(http.StatusOK, "Ollama is running")
		})

		r.Handle(method, "/api/tags", s.ListModelsHandler)
		r.Handle(method, "/api/version", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{"version": version.Version})
		})
	}

	return r
}

func Serve(ln net.Listener) error {
	level := slog.LevelInfo
xuxzh1's avatar
init  
xuxzh1 committed
1119
	if envconfig.Debug() {
mashun1's avatar
v1  
mashun1 committed
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
		level = slog.LevelDebug
	}

	slog.Info("server config", "env", envconfig.Values())
	handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
		Level:     level,
		AddSource: true,
		ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
			if attr.Key == slog.SourceKey {
				source := attr.Value.Any().(*slog.Source)
				source.File = filepath.Base(source.File)
			}

			return attr
		},
	})

	slog.SetDefault(slog.New(handler))

	blobsDir, err := GetBlobsPath("")
	if err != nil {
		return err
	}
	if err := fixBlobs(blobsDir); err != nil {
		return err
	}

xuxzh1's avatar
init  
xuxzh1 committed
1147
	if !envconfig.NoPrune() {
mashun1's avatar
v1  
mashun1 committed
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
		// clean up unused layers and manifests
		if err := PruneLayers(); err != nil {
			return err
		}

		manifestsPath, err := GetManifestPath()
		if err != nil {
			return err
		}

		if err := PruneDirectory(manifestsPath); err != nil {
			return err
		}
	}

	ctx, done := context.WithCancel(context.Background())
	schedCtx, schedDone := context.WithCancel(ctx)
	sched := InitScheduler(schedCtx)
	s := &Server{addr: ln.Addr(), sched: sched}
xuxzh1's avatar
init  
xuxzh1 committed
1167
1168

	http.Handle("/", s.GenerateRoutes())
mashun1's avatar
v1  
mashun1 committed
1169
1170
1171

	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
	srvr := &http.Server{
xuxzh1's avatar
init  
xuxzh1 committed
1172
1173
1174
1175
1176
1177
1178
1179
1180
		// 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,
mashun1's avatar
v1  
mashun1 committed
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
	}

	// listen for a ctrl+c and stop any loaded llm
	signals := make(chan os.Signal, 1)
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		<-signals
		srvr.Close()
		schedDone()
		sched.unloadAllRunners()
		gpu.Cleanup()
		done()
	}()

	if err := llm.Init(); err != nil {
		return fmt.Errorf("unable to initialize llm library %w", err)
	}

	s.sched.Run(schedCtx)

	// 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
	gpus := gpu.GetGPUInfo()
	gpus.LogDetails()

	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()
	return nil
}

func waitForStream(c *gin.Context, ch chan interface{}) {
	c.Header("Content-Type", "application/json")
	for resp := range ch {
		switch r := resp.(type) {
		case api.ProgressResponse:
			if r.Status == "success" {
				c.JSON(http.StatusOK, r)
				return
			}
		case gin.H:
xuxzh1's avatar
init  
xuxzh1 committed
1226
1227
1228
1229
			status, ok := r["status"].(int)
			if !ok {
				status = http.StatusInternalServerError
			}
mashun1's avatar
v1  
mashun1 committed
1230
			if errorMsg, ok := r["error"].(string); ok {
xuxzh1's avatar
init  
xuxzh1 committed
1231
				c.JSON(status, gin.H{"error": errorMsg})
mashun1's avatar
v1  
mashun1 committed
1232
1233
				return
			} else {
xuxzh1's avatar
init  
xuxzh1 committed
1234
				c.JSON(status, gin.H{"error": "unexpected error format in progress response"})
mashun1's avatar
v1  
mashun1 committed
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
				return
			}
		default:
			c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
			return
		}
	}
	c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
}

func streamResponse(c *gin.Context, ch chan any) {
	c.Header("Content-Type", "application/x-ndjson")
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

		bts, err := json.Marshal(val)
		if err != nil {
			slog.Info(fmt.Sprintf("streamResponse: json.Marshal failed with %s", err))
			return false
		}

		// Delineate chunks with new-line delimiter
		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
			return false
		}

		return true
	})
}

func (s *Server) ProcessHandler(c *gin.Context) {
xuxzh1's avatar
init  
xuxzh1 committed
1271
	models := []api.ProcessModelResponse{}
mashun1's avatar
v1  
mashun1 committed
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282

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

xuxzh1's avatar
init  
xuxzh1 committed
1283
		mr := api.ProcessModelResponse{
mashun1's avatar
v1  
mashun1 committed
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
			Model:     model.ShortName,
			Name:      model.ShortName,
			Size:      int64(v.estimatedTotal),
			SizeVRAM:  int64(v.estimatedVRAM),
			Digest:    model.Digest,
			Details:   modelDetails,
			ExpiresAt: v.expiresAt,
		}
		// 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)
		}

		models = append(models, mr)
	}

xuxzh1's avatar
init  
xuxzh1 committed
1303
1304
1305
1306
	slices.SortStableFunc(models, func(i, j api.ProcessModelResponse) int {
		// longest duration remaining listed first
		return cmp.Compare(j.ExpiresAt.Unix(), i.ExpiresAt.Unix())
	})
mashun1's avatar
v1  
mashun1 committed
1307

xuxzh1's avatar
init  
xuxzh1 committed
1308
	c.JSON(http.StatusOK, api.ProcessResponse{Models: models})
mashun1's avatar
v1  
mashun1 committed
1309
1310
1311
1312
1313
1314
}

func (s *Server) ChatHandler(c *gin.Context) {
	checkpointStart := time.Now()

	var req api.ChatRequest
xuxzh1's avatar
init  
xuxzh1 committed
1315
	if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
mashun1's avatar
v1  
mashun1 committed
1316
1317
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
		return
xuxzh1's avatar
init  
xuxzh1 committed
1318
	} else if err != nil {
mashun1's avatar
v1  
mashun1 committed
1319
1320
1321
1322
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

xuxzh1's avatar
init  
xuxzh1 committed
1323
1324
1325
	caps := []Capability{CapabilityCompletion}
	if len(req.Tools) > 0 {
		caps = append(caps, CapabilityTools)
mashun1's avatar
v1  
mashun1 committed
1326
1327
	}

xuxzh1's avatar
init  
xuxzh1 committed
1328
1329
1330
	r, m, opts, err := s.scheduleRunner(c.Request.Context(), req.Model, caps, req.Options, req.KeepAlive)
	if errors.Is(err, errCapabilityCompletion) {
		c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("%q does not support chat", req.Model)})
mashun1's avatar
v1  
mashun1 committed
1331
		return
xuxzh1's avatar
init  
xuxzh1 committed
1332
1333
	} else if err != nil {
		handleScheduleError(c, req.Model, err)
mashun1's avatar
v1  
mashun1 committed
1334
1335
1336
1337
1338
		return
	}

	checkpointLoaded := time.Now()

xuxzh1's avatar
init  
xuxzh1 committed
1339
1340
	if len(req.Messages) == 0 {
		c.JSON(http.StatusOK, api.ChatResponse{
mashun1's avatar
v1  
mashun1 committed
1341
			Model:      req.Model,
xuxzh1's avatar
init  
xuxzh1 committed
1342
1343
			CreatedAt:  time.Now().UTC(),
			Message:    api.Message{Role: "assistant"},
mashun1's avatar
v1  
mashun1 committed
1344
1345
			Done:       true,
			DoneReason: "load",
xuxzh1's avatar
init  
xuxzh1 committed
1346
		})
mashun1's avatar
v1  
mashun1 committed
1347
1348
1349
		return
	}

xuxzh1's avatar
init  
xuxzh1 committed
1350
1351
1352
1353
	msgs := append(m.Messages, req.Messages...)
	if req.Messages[0].Role != "system" && m.System != "" {
		msgs = append([]api.Message{{Role: "system", Content: m.System}}, msgs...)
	}
mashun1's avatar
v1  
mashun1 committed
1354

xuxzh1's avatar
init  
xuxzh1 committed
1355
1356
1357
1358
	prompt, images, err := chatPrompt(c.Request.Context(), m, r.Tokenize, opts, msgs, req.Tools)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
mashun1's avatar
v1  
mashun1 committed
1359
1360
	}

xuxzh1's avatar
init  
xuxzh1 committed
1361
	slog.Debug("chat request", "images", len(images), "prompt", prompt)
mashun1's avatar
v1  
mashun1 committed
1362
1363
1364
1365

	ch := make(chan any)
	go func() {
		defer close(ch)
xuxzh1's avatar
init  
xuxzh1 committed
1366
1367
1368
1369
1370
1371
1372
		if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
			Prompt:  prompt,
			Images:  images,
			Format:  req.Format,
			Options: opts,
		}, func(r llm.CompletionResponse) {
			res := api.ChatResponse{
mashun1's avatar
v1  
mashun1 committed
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
				Model:      req.Model,
				CreatedAt:  time.Now().UTC(),
				Message:    api.Message{Role: "assistant", Content: r.Content},
				Done:       r.Done,
				DoneReason: r.DoneReason,
				Metrics: api.Metrics{
					PromptEvalCount:    r.PromptEvalCount,
					PromptEvalDuration: r.PromptEvalDuration,
					EvalCount:          r.EvalCount,
					EvalDuration:       r.EvalDuration,
				},
			}

			if r.Done {
xuxzh1's avatar
init  
xuxzh1 committed
1387
1388
				res.TotalDuration = time.Since(checkpointStart)
				res.LoadDuration = checkpointLoaded.Sub(checkpointStart)
mashun1's avatar
v1  
mashun1 committed
1389
1390
			}

xuxzh1's avatar
init  
xuxzh1 committed
1391
1392
			ch <- res
		}); err != nil {
mashun1's avatar
v1  
mashun1 committed
1393
1394
1395
1396
1397
			ch <- gin.H{"error": err.Error()}
		}
	}()

	if req.Stream != nil && !*req.Stream {
xuxzh1's avatar
init  
xuxzh1 committed
1398
		var resp api.ChatResponse
mashun1's avatar
v1  
mashun1 committed
1399
		var sb strings.Builder
xuxzh1's avatar
init  
xuxzh1 committed
1400
1401
		for rr := range ch {
			switch t := rr.(type) {
mashun1's avatar
v1  
mashun1 committed
1402
			case api.ChatResponse:
xuxzh1's avatar
init  
xuxzh1 committed
1403
1404
				sb.WriteString(t.Message.Content)
				resp = t
mashun1's avatar
v1  
mashun1 committed
1405
			case gin.H:
xuxzh1's avatar
init  
xuxzh1 committed
1406
1407
1408
				msg, ok := t["error"].(string)
				if !ok {
					msg = "unexpected error format in response"
mashun1's avatar
v1  
mashun1 committed
1409
				}
xuxzh1's avatar
init  
xuxzh1 committed
1410
1411
1412

				c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
				return
mashun1's avatar
v1  
mashun1 committed
1413
			default:
xuxzh1's avatar
init  
xuxzh1 committed
1414
				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
mashun1's avatar
v1  
mashun1 committed
1415
1416
1417
1418
				return
			}
		}

xuxzh1's avatar
init  
xuxzh1 committed
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
		resp.Message.Content = sb.String()

		if len(req.Tools) > 0 {
			if toolCalls, ok := m.parseToolCalls(sb.String()); ok {
				resp.Message.ToolCalls = toolCalls
				resp.Message.Content = ""
			}
		}

		c.JSON(http.StatusOK, resp)
mashun1's avatar
v1  
mashun1 committed
1429
1430
1431
1432
1433
1434
		return
	}

	streamResponse(c, ch)
}

xuxzh1's avatar
init  
xuxzh1 committed
1435
1436
1437
1438
1439
func handleScheduleError(c *gin.Context, name string, err error) {
	switch {
	case errors.Is(err, errCapabilities), errors.Is(err, errRequired):
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	case errors.Is(err, context.Canceled):
mashun1's avatar
v1  
mashun1 committed
1440
		c.JSON(499, gin.H{"error": "request canceled"})
xuxzh1's avatar
init  
xuxzh1 committed
1441
	case errors.Is(err, ErrMaxQueue):
mashun1's avatar
v1  
mashun1 committed
1442
		c.JSON(http.StatusServiceUnavailable, gin.H{"error": err.Error()})
xuxzh1's avatar
init  
xuxzh1 committed
1443
1444
1445
1446
	case errors.Is(err, os.ErrNotExist):
		c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model %q not found, try pulling it first", name)})
	default:
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
mashun1's avatar
v1  
mashun1 committed
1447
1448
	}
}