| 
									
										
										
										
											2023-07-04 03:22:44 +08:00
										 |  |  | package server | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | import ( | 
					
						
							| 
									
										
										
										
											2024-05-01 01:55:19 +08:00
										 |  |  | 	"cmp" | 
					
						
							| 
									
										
										
										
											2023-07-26 05:08:51 +08:00
										 |  |  | 	"context" | 
					
						
							| 
									
										
										
										
											2023-07-07 01:40:11 +08:00
										 |  |  | 	"encoding/json" | 
					
						
							| 
									
										
										
										
											2023-10-07 04:06:20 +08:00
										 |  |  | 	"errors" | 
					
						
							| 
									
										
										
										
											2023-07-22 14:02:12 +08:00
										 |  |  | 	"fmt" | 
					
						
							| 
									
										
										
										
											2023-07-04 03:22:44 +08:00
										 |  |  | 	"io" | 
					
						
							| 
									
										
										
										
											2023-10-07 04:06:20 +08:00
										 |  |  | 	"io/fs" | 
					
						
							| 
									
										
										
										
											2024-01-19 02:52:01 +08:00
										 |  |  | 	"log/slog" | 
					
						
							| 
									
										
										
										
											2024-03-14 04:29:40 +08:00
										 |  |  | 	"math" | 
					
						
							| 
									
										
										
										
											2023-07-04 03:22:44 +08:00
										 |  |  | 	"net" | 
					
						
							|  |  |  | 	"net/http" | 
					
						
							| 
									
										
										
										
											2024-03-09 14:23:47 +08:00
										 |  |  | 	"net/netip" | 
					
						
							| 
									
										
										
										
											2023-07-08 03:27:43 +08:00
										 |  |  | 	"os" | 
					
						
							| 
									
										
										
										
											2023-08-31 04:35:03 +08:00
										 |  |  | 	"os/signal" | 
					
						
							| 
									
										
										
										
											2023-07-15 08:27:14 +08:00
										 |  |  | 	"path/filepath" | 
					
						
							| 
									
										
										
										
											2024-05-22 12:30:52 +08:00
										 |  |  | 	"slices" | 
					
						
							| 
									
										
										
										
											2024-03-14 04:29:40 +08:00
										 |  |  | 	"strconv" | 
					
						
							| 
									
										
										
										
											2023-07-07 01:40:11 +08:00
										 |  |  | 	"strings" | 
					
						
							| 
									
										
										
										
											2023-08-31 04:35:03 +08:00
										 |  |  | 	"syscall" | 
					
						
							| 
									
										
										
										
											2023-07-13 09:18:06 +08:00
										 |  |  | 	"time" | 
					
						
							| 
									
										
										
										
											2023-07-04 03:22:44 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-07-22 09:01:24 +08:00
										 |  |  | 	"github.com/gin-contrib/cors" | 
					
						
							| 
									
										
										
										
											2023-07-04 03:22:44 +08:00
										 |  |  | 	"github.com/gin-gonic/gin" | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-27 04:04:17 +08:00
										 |  |  | 	"github.com/ollama/ollama/api" | 
					
						
							| 
									
										
										
										
											2024-05-25 05:57:15 +08:00
										 |  |  | 	"github.com/ollama/ollama/envconfig" | 
					
						
							| 
									
										
										
										
											2024-03-27 04:04:17 +08:00
										 |  |  | 	"github.com/ollama/ollama/gpu" | 
					
						
							|  |  |  | 	"github.com/ollama/ollama/llm" | 
					
						
							|  |  |  | 	"github.com/ollama/ollama/openai" | 
					
						
							| 
									
										
										
										
											2024-05-21 02:26:45 +08:00
										 |  |  | 	"github.com/ollama/ollama/parser" | 
					
						
							| 
									
										
										
										
											2024-05-14 09:48:28 +08:00
										 |  |  | 	"github.com/ollama/ollama/types/errtypes" | 
					
						
							| 
									
										
										
										
											2024-04-17 07:22:38 +08:00
										 |  |  | 	"github.com/ollama/ollama/types/model" | 
					
						
							| 
									
										
										
										
											2024-03-27 04:04:17 +08:00
										 |  |  | 	"github.com/ollama/ollama/version" | 
					
						
							| 
									
										
										
										
											2023-07-04 03:22:44 +08:00
										 |  |  | ) | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-08-23 00:48:35 +08:00
										 |  |  | var mode string = gin.DebugMode | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-12-15 08:47:40 +08:00
										 |  |  | type Server struct { | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 	addr  net.Addr | 
					
						
							|  |  |  | 	sched *Scheduler | 
					
						
							| 
									
										
										
										
											2023-12-15 08:47:40 +08:00
										 |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-08-23 00:48:35 +08:00
										 |  |  | func init() { | 
					
						
							|  |  |  | 	switch mode { | 
					
						
							|  |  |  | 	case gin.DebugMode: | 
					
						
							|  |  |  | 	case gin.ReleaseMode: | 
					
						
							|  |  |  | 	case gin.TestMode: | 
					
						
							|  |  |  | 	default: | 
					
						
							|  |  |  | 		mode = gin.DebugMode | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	gin.SetMode(mode) | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-08-15 21:35:39 +08:00
										 |  |  | var defaultSessionDuration = 5 * time.Minute | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-04 01:01:42 +08:00
										 |  |  | 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 | 
					
						
							| 
									
										
										
										
											2023-08-09 03:13:22 +08:00
										 |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-13 03:16:20 +08:00
										 |  |  | func isSupportedImageType(image []byte) bool { | 
					
						
							|  |  |  | 	contentType := http.DetectContentType(image) | 
					
						
							|  |  |  | 	allowedTypes := []string{"image/jpeg", "image/jpg", "image/png"} | 
					
						
							|  |  |  | 	return slices.Contains(allowedTypes, contentType) | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | func (s *Server) GenerateHandler(c *gin.Context) { | 
					
						
							| 
									
										
										
										
											2023-08-09 03:13:22 +08:00
										 |  |  | 	checkpointStart := time.Now() | 
					
						
							|  |  |  | 	var req api.GenerateRequest | 
					
						
							| 
									
										
										
										
											2023-10-19 07:08:42 +08:00
										 |  |  | 	err := c.ShouldBindJSON(&req) | 
					
						
							| 
									
										
										
										
											2023-12-12 05:56:22 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-10-19 07:08:42 +08:00
										 |  |  | 	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()}) | 
					
						
							| 
									
										
										
										
											2023-08-09 03:13:22 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-11-09 06:05:02 +08:00
										 |  |  | 	// validate the request
 | 
					
						
							|  |  |  | 	switch { | 
					
						
							|  |  |  | 	case req.Model == "": | 
					
						
							| 
									
										
										
										
											2023-10-19 06:56:34 +08:00
										 |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"}) | 
					
						
							|  |  |  | 		return | 
					
						
							| 
									
										
										
										
											2023-11-10 08:44:02 +08:00
										 |  |  | 	case len(req.Format) > 0 && req.Format != "json": | 
					
						
							|  |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"}) | 
					
						
							|  |  |  | 		return | 
					
						
							| 
									
										
										
										
											2023-11-09 06:05:02 +08:00
										 |  |  | 	case req.Raw && (req.Template != "" || req.System != "" || len(req.Context) > 0): | 
					
						
							|  |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "raw mode does not support template, system, or context"}) | 
					
						
							|  |  |  | 		return | 
					
						
							| 
									
										
										
										
											2023-10-19 06:56:34 +08:00
										 |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-13 03:16:20 +08:00
										 |  |  | 	for _, img := range req.Images { | 
					
						
							|  |  |  | 		if !isSupportedImageType(img) { | 
					
						
							|  |  |  | 			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "unsupported image format"}) | 
					
						
							|  |  |  | 			return | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-04 01:01:42 +08:00
										 |  |  | 	model, err := GetModel(req.Model) | 
					
						
							| 
									
										
										
										
											2023-08-09 03:13:22 +08:00
										 |  |  | 	if err != nil { | 
					
						
							| 
									
										
										
										
											2023-10-07 04:06:20 +08:00
										 |  |  | 		var pErr *fs.PathError | 
					
						
							| 
									
										
										
										
											2024-01-04 01:01:42 +08:00
										 |  |  | 		if errors.As(err, &pErr) { | 
					
						
							| 
									
										
										
										
											2023-10-07 04:06:20 +08:00
										 |  |  | 			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)}) | 
					
						
							| 
									
										
										
										
											2024-01-04 01:01:42 +08:00
										 |  |  | 			return | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-21 10:37:29 +08:00
										 |  |  | 	if model.IsEmbedding() { | 
					
						
							| 
									
										
										
										
											2024-02-21 10:53:45 +08:00
										 |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "embedding models do not support generate"}) | 
					
						
							| 
									
										
										
										
											2024-02-21 10:37:29 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-04 01:01:42 +08:00
										 |  |  | 	opts, err := modelOptions(model, req.Options) | 
					
						
							|  |  |  | 	if err != nil { | 
					
						
							|  |  |  | 		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-27 06:28:02 +08:00
										 |  |  | 	var sessionDuration time.Duration | 
					
						
							|  |  |  | 	if req.KeepAlive == nil { | 
					
						
							| 
									
										
										
										
											2024-03-14 04:29:40 +08:00
										 |  |  | 		sessionDuration = getDefaultSessionDuration() | 
					
						
							| 
									
										
										
										
											2024-01-27 06:28:02 +08:00
										 |  |  | 	} else { | 
					
						
							|  |  |  | 		sessionDuration = req.KeepAlive.Duration | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 	rCh, eCh := s.sched.GetRunner(c.Request.Context(), model, opts, sessionDuration) | 
					
						
							|  |  |  | 	var runner *runnerRef | 
					
						
							|  |  |  | 	select { | 
					
						
							|  |  |  | 	case runner = <-rCh: | 
					
						
							|  |  |  | 	case err = <-eCh: | 
					
						
							| 
									
										
										
										
											2024-05-04 07:25:57 +08:00
										 |  |  | 		handleErrorResponse(c, err) | 
					
						
							| 
									
										
										
										
											2023-08-09 03:13:22 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 	// an empty request loads the model
 | 
					
						
							| 
									
										
										
										
											2024-02-13 07:06:57 +08:00
										 |  |  | 	// note: for a short while template was used in lieu
 | 
					
						
							|  |  |  | 	// of `raw` mode so we need to check for it too
 | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 	if req.Prompt == "" && req.Template == "" && req.System == "" { | 
					
						
							| 
									
										
										
										
											2023-12-02 03:37:17 +08:00
										 |  |  | 		c.JSON(http.StatusOK, api.GenerateResponse{ | 
					
						
							| 
									
										
										
										
											2024-05-10 04:30:14 +08:00
										 |  |  | 			CreatedAt:  time.Now().UTC(), | 
					
						
							|  |  |  | 			Model:      req.Model, | 
					
						
							|  |  |  | 			Done:       true, | 
					
						
							|  |  |  | 			DoneReason: "load", | 
					
						
							| 
									
										
										
										
											2023-12-16 06:25:12 +08:00
										 |  |  | 		}) | 
					
						
							| 
									
										
										
										
											2023-12-05 07:01:06 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	checkpointLoaded := time.Now() | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 	var prompt string | 
					
						
							|  |  |  | 	switch { | 
					
						
							|  |  |  | 	case req.Raw: | 
					
						
							|  |  |  | 		prompt = req.Prompt | 
					
						
							|  |  |  | 	case req.Prompt != "": | 
					
						
							| 
									
										
										
										
											2024-02-13 07:06:57 +08:00
										 |  |  | 		if req.Template == "" { | 
					
						
							|  |  |  | 			req.Template = model.Template | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-13 07:06:57 +08:00
										 |  |  | 		if req.System == "" { | 
					
						
							|  |  |  | 			req.System = model.System | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 		slog.Debug("generate handler", "prompt", req.Prompt) | 
					
						
							|  |  |  | 		slog.Debug("generate handler", "template", req.Template) | 
					
						
							|  |  |  | 		slog.Debug("generate handler", "system", req.System) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 		var sb strings.Builder | 
					
						
							| 
									
										
										
										
											2024-03-01 03:30:14 +08:00
										 |  |  | 		for i := range req.Images { | 
					
						
							|  |  |  | 			fmt.Fprintf(&sb, "[img-%d] ", i) | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 		sb.WriteString(req.Prompt) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 		p, err := Prompt(req.Template, req.System, sb.String(), "", true) | 
					
						
							|  |  |  | 		if err != nil { | 
					
						
							|  |  |  | 			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 			return | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 		sb.Reset() | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 		if req.Context != nil { | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 			prev, err := runner.llama.Detokenize(c.Request.Context(), req.Context) | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 			if err != nil { | 
					
						
							|  |  |  | 				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 				return | 
					
						
							|  |  |  | 			} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-13 07:06:57 +08:00
										 |  |  | 			sb.WriteString(prev) | 
					
						
							| 
									
										
										
										
											2024-01-29 06:15:56 +08:00
										 |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-13 07:06:57 +08:00
										 |  |  | 		sb.WriteString(p) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 		prompt = sb.String() | 
					
						
							| 
									
										
										
										
											2023-08-09 03:13:22 +08:00
										 |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-01 08:47:26 +08:00
										 |  |  | 	slog.Debug("generate handler", "prompt", prompt) | 
					
						
							| 
									
										
										
										
											2024-01-29 07:22:35 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-12-05 07:01:06 +08:00
										 |  |  | 	ch := make(chan any) | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 	var generated strings.Builder | 
					
						
							| 
									
										
										
										
											2023-12-05 07:01:06 +08:00
										 |  |  | 	go func() { | 
					
						
							|  |  |  | 		defer close(ch) | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-15 01:24:13 +08:00
										 |  |  | 		fn := func(r llm.CompletionResponse) { | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 			// Build up the full response
 | 
					
						
							|  |  |  | 			if _, err := generated.WriteString(r.Content); err != nil { | 
					
						
							|  |  |  | 				ch <- gin.H{"error": err.Error()} | 
					
						
							|  |  |  | 				return | 
					
						
							| 
									
										
										
										
											2023-12-05 07:01:06 +08:00
										 |  |  | 			} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 			resp := api.GenerateResponse{ | 
					
						
							| 
									
										
										
										
											2024-05-10 04:30:14 +08:00
										 |  |  | 				Model:      req.Model, | 
					
						
							|  |  |  | 				CreatedAt:  time.Now().UTC(), | 
					
						
							|  |  |  | 				Done:       r.Done, | 
					
						
							|  |  |  | 				Response:   r.Content, | 
					
						
							|  |  |  | 				DoneReason: r.DoneReason, | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 				Metrics: api.Metrics{ | 
					
						
							|  |  |  | 					PromptEvalCount:    r.PromptEvalCount, | 
					
						
							|  |  |  | 					PromptEvalDuration: r.PromptEvalDuration, | 
					
						
							|  |  |  | 					EvalCount:          r.EvalCount, | 
					
						
							|  |  |  | 					EvalDuration:       r.EvalDuration, | 
					
						
							|  |  |  | 				}, | 
					
						
							| 
									
										
										
										
											2023-12-05 07:01:06 +08:00
										 |  |  | 			} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-12-15 01:15:50 +08:00
										 |  |  | 			if r.Done { | 
					
						
							|  |  |  | 				resp.TotalDuration = time.Since(checkpointStart) | 
					
						
							|  |  |  | 				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 				if !req.Raw { | 
					
						
							| 
									
										
										
										
											2024-02-13 07:06:57 +08:00
										 |  |  | 					p, err := Prompt(req.Template, req.System, req.Prompt, generated.String(), false) | 
					
						
							| 
									
										
										
										
											2023-12-23 06:07:05 +08:00
										 |  |  | 					if err != nil { | 
					
						
							| 
									
										
										
										
											2024-02-13 07:06:57 +08:00
										 |  |  | 						c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							| 
									
										
										
										
											2023-12-23 06:07:05 +08:00
										 |  |  | 						return | 
					
						
							|  |  |  | 					} | 
					
						
							| 
									
										
										
										
											2024-02-13 07:06:57 +08:00
										 |  |  | 
 | 
					
						
							|  |  |  | 					// TODO (jmorganca): encode() should not strip special tokens
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 					tokens, err := runner.llama.Tokenize(c.Request.Context(), p) | 
					
						
							| 
									
										
										
										
											2023-12-15 01:15:50 +08:00
										 |  |  | 					if err != nil { | 
					
						
							|  |  |  | 						ch <- gin.H{"error": err.Error()} | 
					
						
							|  |  |  | 						return | 
					
						
							|  |  |  | 					} | 
					
						
							| 
									
										
										
										
											2024-02-13 07:06:57 +08:00
										 |  |  | 
 | 
					
						
							|  |  |  | 					resp.Context = append(req.Context, tokens...) | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 				} | 
					
						
							|  |  |  | 			} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 			ch <- resp | 
					
						
							| 
									
										
										
										
											2023-12-05 07:01:06 +08:00
										 |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-01 10:56:12 +08:00
										 |  |  | 		var images []llm.ImageData | 
					
						
							| 
									
										
										
										
											2024-02-01 09:39:38 +08:00
										 |  |  | 		for i := range req.Images { | 
					
						
							| 
									
										
										
										
											2024-02-01 10:56:12 +08:00
										 |  |  | 			images = append(images, llm.ImageData{ | 
					
						
							|  |  |  | 				ID:   i, | 
					
						
							|  |  |  | 				Data: req.Images[i], | 
					
						
							|  |  |  | 			}) | 
					
						
							| 
									
										
										
										
											2024-02-01 09:39:38 +08:00
										 |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 		// Start prediction
 | 
					
						
							| 
									
										
										
										
											2024-03-15 01:24:13 +08:00
										 |  |  | 		req := llm.CompletionRequest{ | 
					
						
							| 
									
										
										
										
											2024-01-04 01:01:42 +08:00
										 |  |  | 			Prompt:  prompt, | 
					
						
							|  |  |  | 			Format:  req.Format, | 
					
						
							| 
									
										
										
										
											2024-02-01 09:39:38 +08:00
										 |  |  | 			Images:  images, | 
					
						
							| 
									
										
										
										
											2024-01-04 01:01:42 +08:00
										 |  |  | 			Options: opts, | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 		} | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 		if err := runner.llama.Completion(c.Request.Context(), req, fn); err != nil { | 
					
						
							| 
									
										
										
										
											2023-12-05 07:01:06 +08:00
										 |  |  | 			ch <- gin.H{"error": err.Error()} | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 	}() | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	if req.Stream != nil && !*req.Stream { | 
					
						
							| 
									
										
										
										
											2023-12-10 23:53:38 +08:00
										 |  |  | 		// Accumulate responses into the final response
 | 
					
						
							|  |  |  | 		var final api.GenerateResponse | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 		var sb strings.Builder | 
					
						
							| 
									
										
										
										
											2023-12-05 07:01:06 +08:00
										 |  |  | 		for resp := range ch { | 
					
						
							| 
									
										
										
										
											2023-12-10 23:53:38 +08:00
										 |  |  | 			switch r := resp.(type) { | 
					
						
							|  |  |  | 			case api.GenerateResponse: | 
					
						
							|  |  |  | 				sb.WriteString(r.Response) | 
					
						
							|  |  |  | 				final = r | 
					
						
							|  |  |  | 			case gin.H: | 
					
						
							|  |  |  | 				if errorMsg, ok := r["error"].(string); ok { | 
					
						
							|  |  |  | 					c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg}) | 
					
						
							|  |  |  | 					return | 
					
						
							|  |  |  | 				} else { | 
					
						
							|  |  |  | 					c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in response"}) | 
					
						
							|  |  |  | 					return | 
					
						
							|  |  |  | 				} | 
					
						
							|  |  |  | 			default: | 
					
						
							|  |  |  | 				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error"}) | 
					
						
							| 
									
										
										
										
											2023-12-05 07:01:06 +08:00
										 |  |  | 				return | 
					
						
							|  |  |  | 			} | 
					
						
							|  |  |  | 		} | 
					
						
							| 
									
										
										
										
											2023-12-10 23:53:38 +08:00
										 |  |  | 
 | 
					
						
							|  |  |  | 		final.Response = sb.String() | 
					
						
							|  |  |  | 		c.JSON(http.StatusOK, final) | 
					
						
							| 
									
										
										
										
											2023-12-05 07:01:06 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	streamResponse(c, ch) | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-14 04:29:40 +08:00
										 |  |  | func getDefaultSessionDuration() time.Duration { | 
					
						
							| 
									
										
										
										
											2024-05-25 05:57:15 +08:00
										 |  |  | 	if envconfig.KeepAlive != "" { | 
					
						
							|  |  |  | 		v, err := strconv.Atoi(envconfig.KeepAlive) | 
					
						
							| 
									
										
										
										
											2024-03-14 04:29:40 +08:00
										 |  |  | 		if err != nil { | 
					
						
							| 
									
										
										
										
											2024-05-25 05:57:15 +08:00
										 |  |  | 			d, err := time.ParseDuration(envconfig.KeepAlive) | 
					
						
							| 
									
										
										
										
											2024-03-14 04:29:40 +08:00
										 |  |  | 			if err != nil { | 
					
						
							|  |  |  | 				return defaultSessionDuration | 
					
						
							|  |  |  | 			} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 			if d < 0 { | 
					
						
							|  |  |  | 				return time.Duration(math.MaxInt64) | 
					
						
							|  |  |  | 			} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 			return d | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 		d := time.Duration(v) * time.Second | 
					
						
							|  |  |  | 		if d < 0 { | 
					
						
							|  |  |  | 			return time.Duration(math.MaxInt64) | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 		return d | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	return defaultSessionDuration | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | func (s *Server) EmbeddingsHandler(c *gin.Context) { | 
					
						
							| 
									
										
										
										
											2023-12-05 07:01:06 +08:00
										 |  |  | 	var req api.EmbeddingRequest | 
					
						
							|  |  |  | 	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 == "" { | 
					
						
							|  |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-04 01:01:42 +08:00
										 |  |  | 	model, err := GetModel(req.Model) | 
					
						
							| 
									
										
										
										
											2023-12-05 07:01:06 +08:00
										 |  |  | 	if err != nil { | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 		var pErr *fs.PathError | 
					
						
							| 
									
										
										
										
											2024-01-04 01:01:42 +08:00
										 |  |  | 		if errors.As(err, &pErr) { | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)}) | 
					
						
							| 
									
										
										
										
											2024-01-04 01:01:42 +08:00
										 |  |  | 			return | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	opts, err := modelOptions(model, req.Options) | 
					
						
							|  |  |  | 	if err != nil { | 
					
						
							|  |  |  | 		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							| 
									
										
										
										
											2024-01-27 06:28:02 +08:00
										 |  |  | 
 | 
					
						
							|  |  |  | 	var sessionDuration time.Duration | 
					
						
							|  |  |  | 	if req.KeepAlive == nil { | 
					
						
							| 
									
										
										
										
											2024-03-14 04:29:40 +08:00
										 |  |  | 		sessionDuration = getDefaultSessionDuration() | 
					
						
							| 
									
										
										
										
											2024-01-27 06:28:02 +08:00
										 |  |  | 	} else { | 
					
						
							|  |  |  | 		sessionDuration = req.KeepAlive.Duration | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 	rCh, eCh := s.sched.GetRunner(c.Request.Context(), model, opts, sessionDuration) | 
					
						
							|  |  |  | 	var runner *runnerRef | 
					
						
							|  |  |  | 	select { | 
					
						
							|  |  |  | 	case runner = <-rCh: | 
					
						
							|  |  |  | 	case err = <-eCh: | 
					
						
							| 
									
										
										
										
											2024-05-04 07:25:57 +08:00
										 |  |  | 		handleErrorResponse(c, err) | 
					
						
							| 
									
										
										
										
											2023-12-05 07:01:06 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-01 09:40:56 +08:00
										 |  |  | 	// an empty request loads the model
 | 
					
						
							|  |  |  | 	if req.Prompt == "" { | 
					
						
							|  |  |  | 		c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: []float64{}}) | 
					
						
							| 
									
										
										
										
											2023-08-09 03:13:22 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 	embedding, err := runner.llama.Embedding(c.Request.Context(), req.Prompt) | 
					
						
							| 
									
										
										
										
											2023-08-09 03:13:22 +08:00
										 |  |  | 	if err != nil { | 
					
						
							| 
									
										
										
										
											2024-01-19 02:52:01 +08:00
										 |  |  | 		slog.Info(fmt.Sprintf("embedding generation failed: %v", err)) | 
					
						
							| 
									
										
										
										
											2023-08-09 03:13:22 +08:00
										 |  |  | 		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	resp := api.EmbeddingResponse{ | 
					
						
							|  |  |  | 		Embedding: embedding, | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 	c.JSON(http.StatusOK, resp) | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | func (s *Server) PullModelHandler(c *gin.Context) { | 
					
						
							| 
									
										
										
										
											2023-07-12 02:54:22 +08:00
										 |  |  | 	var req api.PullRequest | 
					
						
							| 
									
										
										
										
											2023-10-19 07:08:42 +08:00
										 |  |  | 	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()}) | 
					
						
							| 
									
										
										
										
											2023-07-12 02:54:22 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-14 06:27:51 +08:00
										 |  |  | 	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()}) | 
					
						
							| 
									
										
										
										
											2023-10-19 06:56:34 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-07-17 08:02:22 +08:00
										 |  |  | 	ch := make(chan any) | 
					
						
							|  |  |  | 	go func() { | 
					
						
							|  |  |  | 		defer close(ch) | 
					
						
							| 
									
										
										
										
											2023-07-19 09:51:30 +08:00
										 |  |  | 		fn := func(r api.ProgressResponse) { | 
					
						
							|  |  |  | 			ch <- r | 
					
						
							| 
									
										
										
										
											2023-07-17 08:02:22 +08:00
										 |  |  | 		} | 
					
						
							| 
									
										
										
										
											2023-07-19 09:51:30 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-15 03:29:49 +08:00
										 |  |  | 		regOpts := ®istryOptions{ | 
					
						
							| 
									
										
										
										
											2023-07-22 06:42:19 +08:00
										 |  |  | 			Insecure: req.Insecure, | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-07-26 05:08:51 +08:00
										 |  |  | 		ctx, cancel := context.WithCancel(c.Request.Context()) | 
					
						
							|  |  |  | 		defer cancel() | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-14 06:27:51 +08:00
										 |  |  | 		if err := PullModel(ctx, name.DisplayShortest(), regOpts, fn); err != nil { | 
					
						
							| 
									
										
										
										
											2023-07-21 03:12:08 +08:00
										 |  |  | 			ch <- gin.H{"error": err.Error()} | 
					
						
							| 
									
										
										
										
											2023-07-17 08:02:22 +08:00
										 |  |  | 		} | 
					
						
							|  |  |  | 	}() | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-10-12 00:54:27 +08:00
										 |  |  | 	if req.Stream != nil && !*req.Stream { | 
					
						
							|  |  |  | 		waitForStream(c, ch) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-07-17 08:02:22 +08:00
										 |  |  | 	streamResponse(c, ch) | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | func (s *Server) PushModelHandler(c *gin.Context) { | 
					
						
							| 
									
										
										
										
											2023-07-17 08:02:22 +08:00
										 |  |  | 	var req api.PushRequest | 
					
						
							| 
									
										
										
										
											2023-10-19 07:08:42 +08:00
										 |  |  | 	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()}) | 
					
						
							| 
									
										
										
										
											2023-07-12 02:54:22 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							| 
									
										
										
										
											2023-07-07 01:40:11 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-12 06:07:54 +08:00
										 |  |  | 	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"}) | 
					
						
							| 
									
										
										
										
											2023-10-19 06:56:34 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-07-17 08:02:22 +08:00
										 |  |  | 	ch := make(chan any) | 
					
						
							|  |  |  | 	go func() { | 
					
						
							|  |  |  | 		defer close(ch) | 
					
						
							| 
									
										
										
										
											2023-07-19 09:51:30 +08:00
										 |  |  | 		fn := func(r api.ProgressResponse) { | 
					
						
							|  |  |  | 			ch <- r | 
					
						
							| 
									
										
										
										
											2023-07-17 08:02:22 +08:00
										 |  |  | 		} | 
					
						
							| 
									
										
										
										
											2023-07-19 09:51:30 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-15 03:29:49 +08:00
										 |  |  | 		regOpts := ®istryOptions{ | 
					
						
							| 
									
										
										
										
											2023-07-22 06:42:19 +08:00
										 |  |  | 			Insecure: req.Insecure, | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-10-10 01:24:27 +08:00
										 |  |  | 		ctx, cancel := context.WithCancel(c.Request.Context()) | 
					
						
							|  |  |  | 		defer cancel() | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-12 06:07:54 +08:00
										 |  |  | 		if err := PushModel(ctx, model, regOpts, fn); err != nil { | 
					
						
							| 
									
										
										
										
											2023-07-21 03:12:08 +08:00
										 |  |  | 			ch <- gin.H{"error": err.Error()} | 
					
						
							| 
									
										
										
										
											2023-07-17 08:02:22 +08:00
										 |  |  | 		} | 
					
						
							|  |  |  | 	}() | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-10-12 00:54:27 +08:00
										 |  |  | 	if req.Stream != nil && !*req.Stream { | 
					
						
							|  |  |  | 		waitForStream(c, ch) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-07-17 08:02:22 +08:00
										 |  |  | 	streamResponse(c, ch) | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-14 06:27:51 +08:00
										 |  |  | 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 { | 
					
						
							|  |  |  | 			return fmt.Errorf("a model with that name already exists") | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	return nil | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | func (s *Server) CreateModelHandler(c *gin.Context) { | 
					
						
							| 
									
										
										
										
											2024-05-09 05:36:08 +08:00
										 |  |  | 	var r api.CreateRequest | 
					
						
							|  |  |  | 	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) { | 
					
						
							| 
									
										
										
										
											2023-10-19 07:08:42 +08:00
										 |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"}) | 
					
						
							|  |  |  | 		return | 
					
						
							| 
									
										
										
										
											2024-05-01 01:55:19 +08:00
										 |  |  | 	} else if err != nil { | 
					
						
							| 
									
										
										
										
											2023-10-19 07:08:42 +08:00
										 |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()}) | 
					
						
							| 
									
										
										
										
											2023-07-13 10:07:15 +08:00
										 |  |  | 		return | 
					
						
							| 
									
										
										
										
											2023-07-17 08:02:22 +08:00
										 |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-09 05:36:08 +08:00
										 |  |  | 	name := model.ParseName(cmp.Or(r.Model, r.Name)) | 
					
						
							| 
									
										
										
										
											2024-05-01 01:55:19 +08:00
										 |  |  | 	if !name.IsValid() { | 
					
						
							| 
									
										
										
										
											2024-05-14 09:48:28 +08:00
										 |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": errtypes.InvalidModelNameErrMsg}) | 
					
						
							| 
									
										
										
										
											2023-11-30 02:33:45 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-14 06:27:51 +08:00
										 |  |  | 	if err := checkNameExists(name); err != nil { | 
					
						
							|  |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-09 05:36:08 +08:00
										 |  |  | 	if r.Path == "" && r.Modelfile == "" { | 
					
						
							| 
									
										
										
										
											2023-11-15 05:45:07 +08:00
										 |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"}) | 
					
						
							| 
									
										
										
										
											2023-11-15 04:30:34 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							| 
									
										
										
										
											2023-11-15 05:45:07 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-09 05:36:08 +08:00
										 |  |  | 	var sr io.Reader = strings.NewReader(r.Modelfile) | 
					
						
							|  |  |  | 	if r.Path != "" && r.Modelfile == "" { | 
					
						
							|  |  |  | 		f, err := os.Open(r.Path) | 
					
						
							| 
									
										
										
										
											2023-11-15 05:45:07 +08:00
										 |  |  | 		if err != nil { | 
					
						
							|  |  |  | 			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)}) | 
					
						
							|  |  |  | 			return | 
					
						
							|  |  |  | 		} | 
					
						
							| 
									
										
										
										
											2024-05-01 01:55:19 +08:00
										 |  |  | 		defer f.Close() | 
					
						
							| 
									
										
										
										
											2023-11-15 05:45:07 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-09 05:36:08 +08:00
										 |  |  | 		sr = f | 
					
						
							| 
									
										
										
										
											2023-11-15 05:45:07 +08:00
										 |  |  | 	} | 
					
						
							| 
									
										
										
										
											2023-11-15 04:30:34 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-09 05:36:08 +08:00
										 |  |  | 	f, err := parser.ParseFile(sr) | 
					
						
							| 
									
										
										
										
											2023-11-15 04:30:34 +08:00
										 |  |  | 	if err != nil { | 
					
						
							|  |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-07-12 02:54:22 +08:00
										 |  |  | 	ch := make(chan any) | 
					
						
							| 
									
										
										
										
											2023-07-15 05:15:53 +08:00
										 |  |  | 	go func() { | 
					
						
							|  |  |  | 		defer close(ch) | 
					
						
							| 
									
										
										
										
											2023-07-26 02:25:13 +08:00
										 |  |  | 		fn := func(resp api.ProgressResponse) { | 
					
						
							|  |  |  | 			ch <- resp | 
					
						
							| 
									
										
										
										
											2023-07-17 08:02:22 +08:00
										 |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-07-26 05:08:51 +08:00
										 |  |  | 		ctx, cancel := context.WithCancel(c.Request.Context()) | 
					
						
							|  |  |  | 		defer cancel() | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-09 05:36:08 +08:00
										 |  |  | 		quantization := cmp.Or(r.Quantize, r.Quantization) | 
					
						
							|  |  |  | 		if err := CreateModel(ctx, name, filepath.Dir(r.Path), strings.ToUpper(quantization), f, fn); err != nil { | 
					
						
							| 
									
										
										
										
											2023-07-21 03:12:08 +08:00
										 |  |  | 			ch <- gin.H{"error": err.Error()} | 
					
						
							| 
									
										
										
										
											2023-07-17 08:02:22 +08:00
										 |  |  | 		} | 
					
						
							| 
									
										
										
										
											2023-07-15 05:15:53 +08:00
										 |  |  | 	}() | 
					
						
							| 
									
										
										
										
											2023-07-08 06:29:17 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-09 05:36:08 +08:00
										 |  |  | 	if r.Stream != nil && !*r.Stream { | 
					
						
							| 
									
										
										
										
											2023-10-12 00:54:27 +08:00
										 |  |  | 		waitForStream(c, ch) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-07-15 05:15:53 +08:00
										 |  |  | 	streamResponse(c, ch) | 
					
						
							| 
									
										
										
										
											2023-07-06 03:37:33 +08:00
										 |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | func (s *Server) DeleteModelHandler(c *gin.Context) { | 
					
						
							| 
									
										
										
										
											2024-04-18 08:23:19 +08:00
										 |  |  | 	var r api.DeleteRequest | 
					
						
							|  |  |  | 	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) { | 
					
						
							| 
									
										
										
										
											2023-10-19 07:08:42 +08:00
										 |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"}) | 
					
						
							|  |  |  | 		return | 
					
						
							| 
									
										
										
										
											2024-04-18 08:23:19 +08:00
										 |  |  | 	} else if err != nil { | 
					
						
							| 
									
										
										
										
											2023-10-19 07:08:42 +08:00
										 |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()}) | 
					
						
							| 
									
										
										
										
											2023-07-21 07:09:23 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-04-18 08:23:19 +08:00
										 |  |  | 	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))}) | 
					
						
							| 
									
										
										
										
											2023-07-22 14:02:12 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							| 
									
										
										
										
											2023-09-27 08:28:14 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-04-18 08:23:19 +08:00
										 |  |  | 	m, err := ParseNamedManifest(n) | 
					
						
							| 
									
										
										
										
											2023-09-27 08:28:14 +08:00
										 |  |  | 	if err != nil { | 
					
						
							|  |  |  | 		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-04-18 08:23:19 +08:00
										 |  |  | 	if err := m.Remove(); err != nil { | 
					
						
							| 
									
										
										
										
											2023-09-27 08:28:14 +08:00
										 |  |  | 		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							| 
									
										
										
										
											2024-05-09 05:36:08 +08:00
										 |  |  | 
 | 
					
						
							|  |  |  | 	if err := m.RemoveLayers(); err != nil { | 
					
						
							|  |  |  | 		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							| 
									
										
										
										
											2023-07-21 07:09:23 +08:00
										 |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | func (s *Server) ShowModelHandler(c *gin.Context) { | 
					
						
							| 
									
										
										
										
											2023-09-07 02:04:17 +08:00
										 |  |  | 	var req api.ShowRequest | 
					
						
							| 
									
										
										
										
											2023-10-19 07:08:42 +08:00
										 |  |  | 	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()}) | 
					
						
							| 
									
										
										
										
											2023-09-07 02:04:17 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-12 06:07:54 +08:00
										 |  |  | 	if req.Model != "" { | 
					
						
							| 
									
										
										
										
											2024-01-19 07:36:50 +08:00
										 |  |  | 		// noop
 | 
					
						
							| 
									
										
										
										
											2024-01-12 06:07:54 +08:00
										 |  |  | 	} else if req.Name != "" { | 
					
						
							| 
									
										
										
										
											2024-01-19 07:36:50 +08:00
										 |  |  | 		req.Model = req.Name | 
					
						
							| 
									
										
										
										
											2024-01-12 06:07:54 +08:00
										 |  |  | 	} else { | 
					
						
							| 
									
										
										
										
											2024-01-05 09:23:11 +08:00
										 |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"}) | 
					
						
							| 
									
										
										
										
											2023-10-19 06:56:34 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-05 09:23:11 +08:00
										 |  |  | 	resp, err := GetModelInfo(req) | 
					
						
							| 
									
										
										
										
											2023-09-07 02:04:17 +08:00
										 |  |  | 	if err != nil { | 
					
						
							| 
									
										
										
										
											2024-06-16 11:53:56 +08:00
										 |  |  | 		switch { | 
					
						
							|  |  |  | 		case os.IsNotExist(err): | 
					
						
							| 
									
										
										
										
											2024-01-19 07:36:50 +08:00
										 |  |  | 			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)}) | 
					
						
							| 
									
										
										
										
											2024-06-16 11:53:56 +08:00
										 |  |  | 		case err.Error() == "invalid model name": | 
					
						
							|  |  |  | 			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		default: | 
					
						
							| 
									
										
										
										
											2023-09-07 02:04:17 +08:00
										 |  |  | 			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	c.JSON(http.StatusOK, resp) | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-05 09:23:11 +08:00
										 |  |  | func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) { | 
					
						
							| 
									
										
										
										
											2024-06-16 11:53:56 +08:00
										 |  |  | 	m, err := GetModel(req.Model) | 
					
						
							| 
									
										
										
										
											2023-09-07 02:04:17 +08:00
										 |  |  | 	if err != nil { | 
					
						
							|  |  |  | 		return nil, err | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-12-12 05:56:22 +08:00
										 |  |  | 	modelDetails := api.ModelDetails{ | 
					
						
							| 
									
										
										
										
											2024-06-16 11:53:56 +08:00
										 |  |  | 		ParentModel:       m.ParentModel, | 
					
						
							|  |  |  | 		Format:            m.Config.ModelFormat, | 
					
						
							|  |  |  | 		Family:            m.Config.ModelFamily, | 
					
						
							|  |  |  | 		Families:          m.Config.ModelFamilies, | 
					
						
							|  |  |  | 		ParameterSize:     m.Config.ModelType, | 
					
						
							|  |  |  | 		QuantizationLevel: m.Config.FileType, | 
					
						
							| 
									
										
										
										
											2023-12-12 05:56:22 +08:00
										 |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-05 09:23:11 +08:00
										 |  |  | 	if req.System != "" { | 
					
						
							| 
									
										
										
										
											2024-06-16 11:53:56 +08:00
										 |  |  | 		m.System = req.System | 
					
						
							| 
									
										
										
										
											2024-01-05 09:23:11 +08:00
										 |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	if req.Template != "" { | 
					
						
							| 
									
										
										
										
											2024-06-16 11:53:56 +08:00
										 |  |  | 		m.Template = req.Template | 
					
						
							| 
									
										
										
										
											2024-01-05 09:23:11 +08:00
										 |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-26 04:12:36 +08:00
										 |  |  | 	msgs := make([]api.Message, 0) | 
					
						
							| 
									
										
										
										
											2024-06-16 11:53:56 +08:00
										 |  |  | 	for _, msg := range m.Messages { | 
					
						
							| 
									
										
										
										
											2024-01-26 04:12:36 +08:00
										 |  |  | 		msgs = append(msgs, api.Message{Role: msg.Role, Content: msg.Content}) | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-06-16 11:53:56 +08:00
										 |  |  | 	n := model.ParseName(req.Model) | 
					
						
							|  |  |  | 	if !n.IsValid() { | 
					
						
							|  |  |  | 		return nil, fmt.Errorf("invalid model name") | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	manifest, err := ParseNamedManifest(n) | 
					
						
							|  |  |  | 	if err != nil { | 
					
						
							|  |  |  | 		return nil, err | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-09-07 02:04:17 +08:00
										 |  |  | 	resp := &api.ShowResponse{ | 
					
						
							| 
									
										
										
										
											2024-06-16 11:53:56 +08:00
										 |  |  | 		License:    strings.Join(m.License, "\n"), | 
					
						
							|  |  |  | 		System:     m.System, | 
					
						
							|  |  |  | 		Template:   m.Template, | 
					
						
							|  |  |  | 		Details:    modelDetails, | 
					
						
							|  |  |  | 		Messages:   msgs, | 
					
						
							|  |  |  | 		ModifiedAt: manifest.fi.ModTime(), | 
					
						
							| 
									
										
										
										
											2023-09-07 02:04:17 +08:00
										 |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	var params []string | 
					
						
							|  |  |  | 	cs := 30 | 
					
						
							| 
									
										
										
										
											2024-06-16 11:53:56 +08:00
										 |  |  | 	for k, v := range m.Options { | 
					
						
							| 
									
										
										
										
											2023-09-07 02:04:17 +08:00
										 |  |  | 		switch val := v.(type) { | 
					
						
							|  |  |  | 		case []interface{}: | 
					
						
							|  |  |  | 			for _, nv := range val { | 
					
						
							| 
									
										
										
										
											2024-01-17 02:34:44 +08:00
										 |  |  | 				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv)) | 
					
						
							| 
									
										
										
										
											2023-09-07 02:04:17 +08:00
										 |  |  | 			} | 
					
						
							| 
									
										
										
										
											2024-01-17 02:34:44 +08:00
										 |  |  | 		default: | 
					
						
							|  |  |  | 			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v)) | 
					
						
							| 
									
										
										
										
											2023-09-07 02:04:17 +08:00
										 |  |  | 		} | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 	resp.Parameters = strings.Join(params, "\n") | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-05 09:23:11 +08:00
										 |  |  | 	for k, v := range req.Options { | 
					
						
							|  |  |  | 		if _, ok := req.Options[k]; ok { | 
					
						
							| 
									
										
										
										
											2024-06-16 11:53:56 +08:00
										 |  |  | 			m.Options[k] = v | 
					
						
							| 
									
										
										
										
											2024-01-05 09:23:11 +08:00
										 |  |  | 		} | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-04-27 07:59:31 +08:00
										 |  |  | 	var sb strings.Builder | 
					
						
							| 
									
										
										
										
											2024-05-15 06:34:29 +08:00
										 |  |  | 	fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"") | 
					
						
							| 
									
										
										
										
											2024-04-27 07:59:31 +08:00
										 |  |  | 	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:") | 
					
						
							| 
									
										
										
										
											2024-06-16 11:53:56 +08:00
										 |  |  | 	fmt.Fprintf(&sb, "# FROM %s\n\n", m.ShortName) | 
					
						
							|  |  |  | 	fmt.Fprint(&sb, m.String()) | 
					
						
							| 
									
										
										
										
											2024-04-27 07:59:31 +08:00
										 |  |  | 	resp.Modelfile = sb.String() | 
					
						
							| 
									
										
										
										
											2024-01-05 09:23:11 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-06-20 05:19:02 +08:00
										 |  |  | 	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 | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-09-07 02:04:17 +08:00
										 |  |  | 	return resp, nil | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-06-20 05:19:02 +08:00
										 |  |  | func getKVData(digest string, verbose bool) (llm.KV, error) { | 
					
						
							|  |  |  | 	kvData, err := llm.LoadModel(digest) | 
					
						
							|  |  |  | 	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 | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | func (s *Server) ListModelsHandler(c *gin.Context) { | 
					
						
							| 
									
										
										
										
											2024-05-07 07:34:13 +08:00
										 |  |  | 	ms, err := Manifests() | 
					
						
							| 
									
										
										
										
											2023-07-19 00:09:45 +08:00
										 |  |  | 	if err != nil { | 
					
						
							|  |  |  | 		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							| 
									
										
										
										
											2023-08-31 02:14:12 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-06-07 01:11:45 +08:00
										 |  |  | 	models := []api.ListModelResponse{} | 
					
						
							| 
									
										
										
										
											2024-05-07 07:34:13 +08:00
										 |  |  | 	for n, m := range ms { | 
					
						
							|  |  |  | 		f, err := m.Config.Open() | 
					
						
							|  |  |  | 		if err != nil { | 
					
						
							|  |  |  | 			slog.Warn("bad manifest filepath", "name", n, "error", err) | 
					
						
							|  |  |  | 			continue | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 		defer f.Close() | 
					
						
							| 
									
										
										
										
											2024-04-18 05:54:14 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-07 07:34:13 +08:00
										 |  |  | 		var cf ConfigV2 | 
					
						
							|  |  |  | 		if err := json.NewDecoder(f).Decode(&cf); err != nil { | 
					
						
							|  |  |  | 			slog.Warn("bad manifest config", "name", n, "error", err) | 
					
						
							|  |  |  | 			continue | 
					
						
							| 
									
										
										
										
											2023-07-19 00:09:45 +08:00
										 |  |  | 		} | 
					
						
							| 
									
										
										
										
											2023-08-31 02:14:12 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-07 07:34:13 +08:00
										 |  |  | 		// tag should never be masked
 | 
					
						
							| 
									
										
										
										
											2024-06-07 01:11:45 +08:00
										 |  |  | 		models = append(models, api.ListModelResponse{ | 
					
						
							| 
									
										
										
										
											2024-05-07 07:34:13 +08:00
										 |  |  | 			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, | 
					
						
							|  |  |  | 			}, | 
					
						
							|  |  |  | 		}) | 
					
						
							| 
									
										
										
										
											2023-07-19 00:09:45 +08:00
										 |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-06-07 01:11:45 +08:00
										 |  |  | 	slices.SortStableFunc(models, func(i, j api.ListModelResponse) int { | 
					
						
							| 
									
										
										
										
											2024-04-18 05:54:14 +08:00
										 |  |  | 		// most recently modified first
 | 
					
						
							|  |  |  | 		return cmp.Compare(j.ModifiedAt.Unix(), i.ModifiedAt.Unix()) | 
					
						
							|  |  |  | 	}) | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-07-20 06:00:28 +08:00
										 |  |  | 	c.JSON(http.StatusOK, api.ListResponse{Models: models}) | 
					
						
							| 
									
										
										
										
											2023-07-19 00:09:45 +08:00
										 |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | func (s *Server) CopyModelHandler(c *gin.Context) { | 
					
						
							| 
									
										
										
										
											2024-04-17 07:22:38 +08:00
										 |  |  | 	var r api.CopyRequest | 
					
						
							|  |  |  | 	if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) { | 
					
						
							| 
									
										
										
										
											2023-10-19 07:08:42 +08:00
										 |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"}) | 
					
						
							|  |  |  | 		return | 
					
						
							| 
									
										
										
										
											2024-04-17 07:22:38 +08:00
										 |  |  | 	} else if err != nil { | 
					
						
							| 
									
										
										
										
											2023-10-19 07:08:42 +08:00
										 |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()}) | 
					
						
							| 
									
										
										
										
											2023-07-24 23:27:28 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-04-17 07:22:38 +08:00
										 |  |  | 	src := model.ParseName(r.Source) | 
					
						
							|  |  |  | 	if !src.IsValid() { | 
					
						
							| 
									
										
										
										
											2024-05-02 03:39:05 +08:00
										 |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("source %q is invalid", r.Source)}) | 
					
						
							|  |  |  | 		return | 
					
						
							| 
									
										
										
										
											2023-10-19 06:56:34 +08:00
										 |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-04-17 07:22:38 +08:00
										 |  |  | 	dst := model.ParseName(r.Destination) | 
					
						
							|  |  |  | 	if !dst.IsValid() { | 
					
						
							| 
									
										
										
										
											2024-05-08 08:35:52 +08:00
										 |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("destination %q is invalid", r.Destination)}) | 
					
						
							| 
									
										
										
										
											2023-07-24 23:27:28 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							| 
									
										
										
										
											2024-04-17 07:22:38 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-14 06:27:51 +08:00
										 |  |  | 	if err := checkNameExists(dst); err != nil { | 
					
						
							|  |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-04-17 07:22:38 +08:00
										 |  |  | 	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()}) | 
					
						
							|  |  |  | 	} | 
					
						
							| 
									
										
										
										
											2023-07-24 23:27:28 +08:00
										 |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | func (s *Server) HeadBlobHandler(c *gin.Context) { | 
					
						
							| 
									
										
										
										
											2023-11-15 06:07:40 +08:00
										 |  |  | 	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 | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-11-16 05:55:37 +08:00
										 |  |  | 	c.Status(http.StatusOK) | 
					
						
							| 
									
										
										
										
											2023-11-15 06:07:40 +08:00
										 |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | func (s *Server) CreateBlobHandler(c *gin.Context) { | 
					
						
							| 
									
										
										
										
											2024-05-21 05:58:27 +08:00
										 |  |  | 	if ib, ok := intermediateBlobs[c.Param("digest")]; ok { | 
					
						
							|  |  |  | 		p, err := GetBlobsPath(ib) | 
					
						
							| 
									
										
										
										
											2024-05-11 06:48:41 +08:00
										 |  |  | 		if err != nil { | 
					
						
							|  |  |  | 			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 			return | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 		if _, err := os.Stat(p); errors.Is(err, os.ErrNotExist) { | 
					
						
							| 
									
										
										
										
											2024-05-21 05:58:27 +08:00
										 |  |  | 			slog.Info("evicting intermediate blob which no longer exists", "digest", ib) | 
					
						
							|  |  |  | 			delete(intermediateBlobs, c.Param("digest")) | 
					
						
							| 
									
										
										
										
											2024-05-11 06:48:41 +08:00
										 |  |  | 		} else if err != nil { | 
					
						
							|  |  |  | 			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 			return | 
					
						
							|  |  |  | 		} else { | 
					
						
							|  |  |  | 			c.Status(http.StatusOK) | 
					
						
							|  |  |  | 			return | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-04-06 00:30:09 +08:00
										 |  |  | 	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 | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-11-25 04:01:23 +08:00
										 |  |  | 	layer, err := NewLayer(c.Request.Body, "") | 
					
						
							| 
									
										
										
										
											2023-11-18 07:21:57 +08:00
										 |  |  | 	if err != nil { | 
					
						
							|  |  |  | 		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-11-25 04:01:23 +08:00
										 |  |  | 	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)}) | 
					
						
							| 
									
										
										
										
											2023-11-15 06:07:40 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-11-16 05:55:37 +08:00
										 |  |  | 	c.Status(http.StatusCreated) | 
					
						
							| 
									
										
										
										
											2023-11-15 06:07:40 +08:00
										 |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-09 16:22:08 +08:00
										 |  |  | 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 | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-09 14:23:47 +08:00
										 |  |  | func allowedHost(host string) bool { | 
					
						
							| 
									
										
										
										
											2024-03-09 16:22:08 +08:00
										 |  |  | 	if host == "" || host == "localhost" { | 
					
						
							| 
									
										
										
										
											2024-03-09 14:23:47 +08:00
										 |  |  | 		return true | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	if hostname, err := os.Hostname(); err == nil && host == hostname { | 
					
						
							|  |  |  | 		return true | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	var tlds = []string{ | 
					
						
							| 
									
										
										
										
											2024-03-09 15:23:59 +08:00
										 |  |  | 		"localhost", | 
					
						
							|  |  |  | 		"local", | 
					
						
							|  |  |  | 		"internal", | 
					
						
							| 
									
										
										
										
											2023-12-15 08:47:40 +08:00
										 |  |  | 	} | 
					
						
							| 
									
										
										
										
											2023-10-30 23:10:18 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-09 15:29:53 +08:00
										 |  |  | 	// check if the host is a local TLD
 | 
					
						
							| 
									
										
										
										
											2024-03-09 14:23:47 +08:00
										 |  |  | 	for _, tld := range tlds { | 
					
						
							|  |  |  | 		if strings.HasSuffix(host, "."+tld) { | 
					
						
							|  |  |  | 			return true | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-09 15:29:53 +08:00
										 |  |  | 	return false | 
					
						
							| 
									
										
										
										
											2024-03-09 15:23:59 +08:00
										 |  |  | } | 
					
						
							| 
									
										
										
										
											2024-03-09 14:23:47 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-09 15:23:59 +08:00
										 |  |  | func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc { | 
					
						
							|  |  |  | 	return func(c *gin.Context) { | 
					
						
							|  |  |  | 		if addr == nil { | 
					
						
							| 
									
										
										
										
											2024-03-09 14:23:47 +08:00
										 |  |  | 			c.Next() | 
					
						
							|  |  |  | 			return | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-09 16:22:08 +08:00
										 |  |  | 		if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() { | 
					
						
							| 
									
										
										
										
											2024-03-09 14:23:47 +08:00
										 |  |  | 			c.Next() | 
					
						
							|  |  |  | 			return | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 		host, _, err := net.SplitHostPort(c.Request.Host) | 
					
						
							|  |  |  | 		if err != nil { | 
					
						
							|  |  |  | 			host = c.Request.Host | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-09 15:23:59 +08:00
										 |  |  | 		if addr, err := netip.ParseAddr(host); err == nil { | 
					
						
							| 
									
										
										
										
											2024-03-09 16:22:08 +08:00
										 |  |  | 			if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) { | 
					
						
							| 
									
										
										
										
											2024-03-09 15:23:59 +08:00
										 |  |  | 				c.Next() | 
					
						
							|  |  |  | 				return | 
					
						
							|  |  |  | 			} | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-09 14:23:47 +08:00
										 |  |  | 		if allowedHost(host) { | 
					
						
							| 
									
										
										
										
											2024-05-22 13:21:04 +08:00
										 |  |  | 			if c.Request.Method == http.MethodOptions { | 
					
						
							| 
									
										
										
										
											2024-05-09 04:14:00 +08:00
										 |  |  | 				c.AbortWithStatus(http.StatusNoContent) | 
					
						
							|  |  |  | 				return | 
					
						
							|  |  |  | 			} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-09 14:23:47 +08:00
										 |  |  | 			c.Next() | 
					
						
							|  |  |  | 			return | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 		c.AbortWithStatus(http.StatusForbidden) | 
					
						
							|  |  |  | 	} | 
					
						
							| 
									
										
										
										
											2023-12-15 08:47:40 +08:00
										 |  |  | } | 
					
						
							| 
									
										
										
										
											2023-10-30 23:10:18 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-12-15 08:47:40 +08:00
										 |  |  | func (s *Server) GenerateRoutes() http.Handler { | 
					
						
							| 
									
										
										
										
											2023-07-22 09:01:24 +08:00
										 |  |  | 	config := cors.DefaultConfig() | 
					
						
							|  |  |  | 	config.AllowWildcard = true | 
					
						
							| 
									
										
										
										
											2024-01-05 09:55:47 +08:00
										 |  |  | 	config.AllowBrowserExtensions = true | 
					
						
							| 
									
										
										
										
											2024-05-09 04:14:00 +08:00
										 |  |  | 	config.AllowHeaders = []string{"Authorization", "Content-Type", "User-Agent", "Accept", "X-Requested-With"} | 
					
						
							| 
									
										
										
										
											2024-06-07 06:19:03 +08:00
										 |  |  | 	openAIProperties := []string{"lang", "package-version", "os", "arch", "runtime", "runtime-version", "async"} | 
					
						
							|  |  |  | 	for _, prop := range openAIProperties { | 
					
						
							|  |  |  | 		config.AllowHeaders = append(config.AllowHeaders, "x-stainless-"+prop) | 
					
						
							|  |  |  | 	} | 
					
						
							| 
									
										
										
										
											2024-05-05 02:46:01 +08:00
										 |  |  | 	config.AllowOrigins = envconfig.AllowOrigins | 
					
						
							| 
									
										
										
										
											2023-07-22 09:01:24 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-07-06 03:37:33 +08:00
										 |  |  | 	r := gin.Default() | 
					
						
							| 
									
										
										
										
											2023-09-22 03:38:49 +08:00
										 |  |  | 	r.Use( | 
					
						
							|  |  |  | 		cors.New(config), | 
					
						
							| 
									
										
										
										
											2024-03-09 14:23:47 +08:00
										 |  |  | 		allowedHostsMiddleware(s.addr), | 
					
						
							| 
									
										
										
										
											2023-09-22 03:38:49 +08:00
										 |  |  | 	) | 
					
						
							| 
									
										
										
										
											2023-07-06 03:37:33 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 	r.POST("/api/pull", s.PullModelHandler) | 
					
						
							|  |  |  | 	r.POST("/api/generate", s.GenerateHandler) | 
					
						
							|  |  |  | 	r.POST("/api/chat", s.ChatHandler) | 
					
						
							|  |  |  | 	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) | 
					
						
							| 
									
										
										
										
											2024-05-14 08:17:36 +08:00
										 |  |  | 	r.GET("/api/ps", s.ProcessHandler) | 
					
						
							| 
									
										
										
										
											2023-07-04 03:22:44 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-08 06:24:29 +08:00
										 |  |  | 	// Compatibility endpoints
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 	r.POST("/v1/chat/completions", openai.Middleware(), s.ChatHandler) | 
					
						
							| 
									
										
										
										
											2024-02-08 06:24:29 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-09-22 07:38:03 +08:00
										 |  |  | 	for _, method := range []string{http.MethodGet, http.MethodHead} { | 
					
						
							|  |  |  | 		r.Handle(method, "/", func(c *gin.Context) { | 
					
						
							|  |  |  | 			c.String(http.StatusOK, "Ollama is running") | 
					
						
							|  |  |  | 		}) | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 		r.Handle(method, "/api/tags", s.ListModelsHandler) | 
					
						
							| 
									
										
										
										
											2023-10-13 06:45:07 +08:00
										 |  |  | 		r.Handle(method, "/api/version", func(c *gin.Context) { | 
					
						
							|  |  |  | 			c.JSON(http.StatusOK, gin.H{"version": version.Version}) | 
					
						
							|  |  |  | 		}) | 
					
						
							| 
									
										
										
										
											2023-09-22 07:38:03 +08:00
										 |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-12-15 08:47:40 +08:00
										 |  |  | 	return r | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | func Serve(ln net.Listener) error { | 
					
						
							| 
									
										
										
										
											2024-02-01 06:59:32 +08:00
										 |  |  | 	level := slog.LevelInfo | 
					
						
							| 
									
										
										
										
											2024-05-05 02:46:01 +08:00
										 |  |  | 	if envconfig.Debug { | 
					
						
							| 
									
										
										
										
											2024-02-01 06:59:32 +08:00
										 |  |  | 		level = slog.LevelDebug | 
					
						
							| 
									
										
										
										
											2024-01-19 02:52:01 +08:00
										 |  |  | 	} | 
					
						
							| 
									
										
										
										
											2024-02-01 06:59:32 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-25 05:57:15 +08:00
										 |  |  | 	slog.Info("server config", "env", envconfig.Values()) | 
					
						
							| 
									
										
										
										
											2024-02-01 06:59:32 +08:00
										 |  |  | 	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)) | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-15 11:18:06 +08:00
										 |  |  | 	blobsDir, err := GetBlobsPath("") | 
					
						
							|  |  |  | 	if err != nil { | 
					
						
							|  |  |  | 		return err | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 	if err := fixBlobs(blobsDir); err != nil { | 
					
						
							|  |  |  | 		return err | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-05 02:46:01 +08:00
										 |  |  | 	if !envconfig.NoPrune { | 
					
						
							| 
									
										
										
										
											2023-12-15 08:47:40 +08:00
										 |  |  | 		// 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 | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 	ctx, done := context.WithCancel(context.Background()) | 
					
						
							| 
									
										
										
										
											2024-05-10 06:47:02 +08:00
										 |  |  | 	schedCtx, schedDone := context.WithCancel(ctx) | 
					
						
							|  |  |  | 	sched := InitScheduler(schedCtx) | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 	s := &Server{addr: ln.Addr(), sched: sched} | 
					
						
							| 
									
										
										
										
											2023-12-15 08:47:40 +08:00
										 |  |  | 	r := s.GenerateRoutes() | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-19 02:52:01 +08:00
										 |  |  | 	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version)) | 
					
						
							| 
									
										
										
										
											2023-12-15 08:47:40 +08:00
										 |  |  | 	srvr := &http.Server{ | 
					
						
							| 
									
										
										
										
											2023-07-04 03:22:44 +08:00
										 |  |  | 		Handler: r, | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-08-31 04:35:03 +08:00
										 |  |  | 	// listen for a ctrl+c and stop any loaded llm
 | 
					
						
							|  |  |  | 	signals := make(chan os.Signal, 1) | 
					
						
							| 
									
										
										
										
											2023-09-22 03:38:49 +08:00
										 |  |  | 	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM) | 
					
						
							| 
									
										
										
										
											2023-08-31 04:35:03 +08:00
										 |  |  | 	go func() { | 
					
						
							|  |  |  | 		<-signals | 
					
						
							| 
									
										
										
										
											2024-05-07 07:01:37 +08:00
										 |  |  | 		srvr.Close() | 
					
						
							| 
									
										
										
										
											2024-05-10 06:47:02 +08:00
										 |  |  | 		schedDone() | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 		sched.unloadAllRunners() | 
					
						
							| 
									
										
										
										
											2024-03-09 01:45:55 +08:00
										 |  |  | 		gpu.Cleanup() | 
					
						
							| 
									
										
										
										
											2024-05-10 06:47:02 +08:00
										 |  |  | 		done() | 
					
						
							| 
									
										
										
										
											2023-08-31 04:35:03 +08:00
										 |  |  | 	}() | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-16 09:15:09 +08:00
										 |  |  | 	if err := llm.Init(); err != nil { | 
					
						
							| 
									
										
										
										
											2023-11-30 03:00:37 +08:00
										 |  |  | 		return fmt.Errorf("unable to initialize llm library %w", err) | 
					
						
							|  |  |  | 	} | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-10 06:47:02 +08:00
										 |  |  | 	s.sched.Run(schedCtx) | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 
 | 
					
						
							|  |  |  | 	// 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
 | 
					
						
							| 
									
										
										
										
											2024-05-08 05:54:26 +08:00
										 |  |  | 	gpus := gpu.GetGPUInfo() | 
					
						
							|  |  |  | 	gpus.LogDetails() | 
					
						
							| 
									
										
										
										
											2023-09-12 23:04:35 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-10 06:47:02 +08:00
										 |  |  | 	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() | 
					
						
							| 
									
										
										
										
											2024-05-17 07:25:38 +08:00
										 |  |  | 	return nil | 
					
						
							| 
									
										
										
										
											2023-07-04 03:22:44 +08:00
										 |  |  | } | 
					
						
							| 
									
										
										
										
											2023-07-07 01:40:11 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-10-12 00:54:27 +08:00
										 |  |  | 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: | 
					
						
							|  |  |  | 			if errorMsg, ok := r["error"].(string); ok { | 
					
						
							|  |  |  | 				c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg}) | 
					
						
							|  |  |  | 				return | 
					
						
							|  |  |  | 			} else { | 
					
						
							|  |  |  | 				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"}) | 
					
						
							|  |  |  | 				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"}) | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-07-15 05:15:53 +08:00
										 |  |  | func streamResponse(c *gin.Context, ch chan any) { | 
					
						
							| 
									
										
										
										
											2023-08-09 12:38:10 +08:00
										 |  |  | 	c.Header("Content-Type", "application/x-ndjson") | 
					
						
							| 
									
										
										
										
											2023-07-12 02:54:22 +08:00
										 |  |  | 	c.Stream(func(w io.Writer) bool { | 
					
						
							|  |  |  | 		val, ok := <-ch | 
					
						
							|  |  |  | 		if !ok { | 
					
						
							|  |  |  | 			return false | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 		bts, err := json.Marshal(val) | 
					
						
							|  |  |  | 		if err != nil { | 
					
						
							| 
									
										
										
										
											2024-01-19 02:52:01 +08:00
										 |  |  | 			slog.Info(fmt.Sprintf("streamResponse: json.Marshal failed with %s", err)) | 
					
						
							| 
									
										
										
										
											2023-07-12 02:54:22 +08:00
										 |  |  | 			return false | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-09-30 12:45:52 +08:00
										 |  |  | 		// Delineate chunks with new-line delimiter
 | 
					
						
							| 
									
										
										
										
											2023-07-12 02:54:22 +08:00
										 |  |  | 		bts = append(bts, '\n') | 
					
						
							|  |  |  | 		if _, err := w.Write(bts); err != nil { | 
					
						
							| 
									
										
										
										
											2024-01-19 02:52:01 +08:00
										 |  |  | 			slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err)) | 
					
						
							| 
									
										
										
										
											2023-07-12 02:54:22 +08:00
										 |  |  | 			return false | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 		return true | 
					
						
							|  |  |  | 	}) | 
					
						
							|  |  |  | } | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-14 08:17:36 +08:00
										 |  |  | func (s *Server) ProcessHandler(c *gin.Context) { | 
					
						
							| 
									
										
										
										
											2024-06-07 01:11:45 +08:00
										 |  |  | 	models := []api.ProcessModelResponse{} | 
					
						
							| 
									
										
										
										
											2024-05-14 08:17:36 +08:00
										 |  |  | 
 | 
					
						
							|  |  |  | 	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, | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-06-07 01:11:45 +08:00
										 |  |  | 		mr := api.ProcessModelResponse{ | 
					
						
							| 
									
										
										
										
											2024-05-14 08:17:36 +08:00
										 |  |  | 			Model:     model.ShortName, | 
					
						
							|  |  |  | 			Name:      model.ShortName, | 
					
						
							|  |  |  | 			Size:      int64(v.estimatedTotal), | 
					
						
							|  |  |  | 			SizeVRAM:  int64(v.estimatedVRAM), | 
					
						
							|  |  |  | 			Digest:    model.Digest, | 
					
						
							|  |  |  | 			Details:   modelDetails, | 
					
						
							|  |  |  | 			ExpiresAt: v.expiresAt, | 
					
						
							|  |  |  | 		} | 
					
						
							| 
									
										
										
										
											2024-05-16 06:43:16 +08:00
										 |  |  | 		// 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) | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-05-14 08:17:36 +08:00
										 |  |  | 		models = append(models, mr) | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-06-07 01:11:45 +08:00
										 |  |  | 	c.JSON(http.StatusOK, api.ProcessResponse{Models: models}) | 
					
						
							| 
									
										
										
										
											2024-05-14 08:17:36 +08:00
										 |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-13 07:06:57 +08:00
										 |  |  | // ChatPrompt builds up a prompt from a series of messages for the currently `loaded` model
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | func chatPrompt(ctx context.Context, runner *runnerRef, template string, messages []api.Message, numCtx int) (string, error) { | 
					
						
							| 
									
										
										
										
											2024-02-13 07:06:57 +08:00
										 |  |  | 	encode := func(s string) ([]int, error) { | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 		return runner.llama.Tokenize(ctx, s) | 
					
						
							| 
									
										
										
										
											2024-02-13 07:06:57 +08:00
										 |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-17 03:42:43 +08:00
										 |  |  | 	prompt, err := ChatPrompt(template, messages, numCtx, encode) | 
					
						
							| 
									
										
										
										
											2024-02-13 07:06:57 +08:00
										 |  |  | 	if err != nil { | 
					
						
							|  |  |  | 		return "", err | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	return prompt, nil | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | func (s *Server) ChatHandler(c *gin.Context) { | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 	checkpointStart := time.Now() | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	var req api.ChatRequest | 
					
						
							|  |  |  | 	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 | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	// validate the request
 | 
					
						
							|  |  |  | 	switch { | 
					
						
							|  |  |  | 	case req.Model == "": | 
					
						
							|  |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	case len(req.Format) > 0 && req.Format != "json": | 
					
						
							|  |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-04 01:01:42 +08:00
										 |  |  | 	model, err := GetModel(req.Model) | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 	if err != nil { | 
					
						
							|  |  |  | 		var pErr *fs.PathError | 
					
						
							| 
									
										
										
										
											2024-01-04 01:01:42 +08:00
										 |  |  | 		if errors.As(err, &pErr) { | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 			c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)}) | 
					
						
							| 
									
										
										
										
											2024-01-04 01:01:42 +08:00
										 |  |  | 			return | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-21 10:37:29 +08:00
										 |  |  | 	if model.IsEmbedding() { | 
					
						
							| 
									
										
										
										
											2024-02-21 10:53:45 +08:00
										 |  |  | 		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "embedding models do not support chat"}) | 
					
						
							| 
									
										
										
										
											2024-02-21 10:37:29 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-01-04 01:01:42 +08:00
										 |  |  | 	opts, err := modelOptions(model, req.Options) | 
					
						
							|  |  |  | 	if err != nil { | 
					
						
							|  |  |  | 		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							| 
									
										
										
										
											2024-01-27 06:28:02 +08:00
										 |  |  | 
 | 
					
						
							|  |  |  | 	var sessionDuration time.Duration | 
					
						
							|  |  |  | 	if req.KeepAlive == nil { | 
					
						
							| 
									
										
										
										
											2024-03-14 04:29:40 +08:00
										 |  |  | 		sessionDuration = getDefaultSessionDuration() | 
					
						
							| 
									
										
										
										
											2024-01-27 06:28:02 +08:00
										 |  |  | 	} else { | 
					
						
							|  |  |  | 		sessionDuration = req.KeepAlive.Duration | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 	rCh, eCh := s.sched.GetRunner(c.Request.Context(), model, opts, sessionDuration) | 
					
						
							|  |  |  | 	var runner *runnerRef | 
					
						
							|  |  |  | 	select { | 
					
						
							|  |  |  | 	case runner = <-rCh: | 
					
						
							|  |  |  | 	case err = <-eCh: | 
					
						
							| 
									
										
										
										
											2024-05-04 07:25:57 +08:00
										 |  |  | 		handleErrorResponse(c, err) | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	checkpointLoaded := time.Now() | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-17 03:42:43 +08:00
										 |  |  | 	// if the first message is not a system message, then add the model's default system message
 | 
					
						
							|  |  |  | 	if len(req.Messages) > 0 && req.Messages[0].Role != "system" { | 
					
						
							|  |  |  | 		req.Messages = append([]api.Message{ | 
					
						
							|  |  |  | 			{ | 
					
						
							|  |  |  | 				Role:    "system", | 
					
						
							|  |  |  | 				Content: model.System, | 
					
						
							|  |  |  | 			}, | 
					
						
							|  |  |  | 		}, req.Messages...) | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 	prompt, err := chatPrompt(c.Request.Context(), runner, model.Template, req.Messages, opts.NumCtx) | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 	if err != nil { | 
					
						
							|  |  |  | 		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							| 
									
										
										
										
											2024-02-01 09:39:38 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-08 08:30:33 +08:00
										 |  |  | 	// an empty request loads the model
 | 
					
						
							| 
									
										
										
										
											2024-02-13 07:06:57 +08:00
										 |  |  | 	if len(req.Messages) == 0 || prompt == "" { | 
					
						
							| 
									
										
										
										
											2024-02-08 08:30:33 +08:00
										 |  |  | 		resp := api.ChatResponse{ | 
					
						
							| 
									
										
										
										
											2024-05-10 04:30:14 +08:00
										 |  |  | 			CreatedAt:  time.Now().UTC(), | 
					
						
							|  |  |  | 			Model:      req.Model, | 
					
						
							|  |  |  | 			Done:       true, | 
					
						
							|  |  |  | 			DoneReason: "load", | 
					
						
							|  |  |  | 			Message:    api.Message{Role: "assistant"}, | 
					
						
							| 
									
										
										
										
											2024-02-08 08:30:33 +08:00
										 |  |  | 		} | 
					
						
							|  |  |  | 		c.JSON(http.StatusOK, resp) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-02-13 07:06:57 +08:00
										 |  |  | 	// only send images that are in the prompt
 | 
					
						
							|  |  |  | 	var i int | 
					
						
							|  |  |  | 	var images []llm.ImageData | 
					
						
							|  |  |  | 	for _, m := range req.Messages { | 
					
						
							|  |  |  | 		for _, img := range m.Images { | 
					
						
							|  |  |  | 			if !isSupportedImageType(img) { | 
					
						
							|  |  |  | 				c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "unsupported image format"}) | 
					
						
							|  |  |  | 				return | 
					
						
							|  |  |  | 			} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 			if strings.Contains(prompt, fmt.Sprintf("[img-%d]", i)) { | 
					
						
							|  |  |  | 				images = append(images, llm.ImageData{Data: img, ID: i}) | 
					
						
							|  |  |  | 			} | 
					
						
							|  |  |  | 			i += 1 | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	slog.Debug("chat handler", "prompt", prompt, "images", len(images)) | 
					
						
							| 
									
										
										
										
											2024-01-29 07:22:35 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 	ch := make(chan any) | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	go func() { | 
					
						
							|  |  |  | 		defer close(ch) | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-15 01:24:13 +08:00
										 |  |  | 		fn := func(r llm.CompletionResponse) { | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 			resp := api.ChatResponse{ | 
					
						
							| 
									
										
										
										
											2024-05-10 04:30:14 +08:00
										 |  |  | 				Model:      req.Model, | 
					
						
							|  |  |  | 				CreatedAt:  time.Now().UTC(), | 
					
						
							|  |  |  | 				Message:    api.Message{Role: "assistant", Content: r.Content}, | 
					
						
							|  |  |  | 				Done:       r.Done, | 
					
						
							|  |  |  | 				DoneReason: r.DoneReason, | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 				Metrics: api.Metrics{ | 
					
						
							|  |  |  | 					PromptEvalCount:    r.PromptEvalCount, | 
					
						
							|  |  |  | 					PromptEvalDuration: r.PromptEvalDuration, | 
					
						
							|  |  |  | 					EvalCount:          r.EvalCount, | 
					
						
							|  |  |  | 					EvalDuration:       r.EvalDuration, | 
					
						
							|  |  |  | 				}, | 
					
						
							|  |  |  | 			} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-12-15 01:15:50 +08:00
										 |  |  | 			if r.Done { | 
					
						
							|  |  |  | 				resp.TotalDuration = time.Since(checkpointStart) | 
					
						
							|  |  |  | 				resp.LoadDuration = checkpointLoaded.Sub(checkpointStart) | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 			} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 			ch <- resp | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2024-03-31 00:50:05 +08:00
										 |  |  | 		if err := runner.llama.Completion(c.Request.Context(), llm.CompletionRequest{ | 
					
						
							| 
									
										
										
										
											2024-01-04 01:01:42 +08:00
										 |  |  | 			Prompt:  prompt, | 
					
						
							|  |  |  | 			Format:  req.Format, | 
					
						
							| 
									
										
										
										
											2024-02-01 11:18:25 +08:00
										 |  |  | 			Images:  images, | 
					
						
							| 
									
										
										
										
											2024-01-04 01:01:42 +08:00
										 |  |  | 			Options: opts, | 
					
						
							| 
									
										
										
										
											2024-03-15 01:24:13 +08:00
										 |  |  | 		}, fn); err != nil { | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 			ch <- gin.H{"error": err.Error()} | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 	}() | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	if req.Stream != nil && !*req.Stream { | 
					
						
							| 
									
										
										
										
											2023-12-10 23:53:38 +08:00
										 |  |  | 		// Accumulate responses into the final response
 | 
					
						
							|  |  |  | 		var final api.ChatResponse | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 		var sb strings.Builder | 
					
						
							|  |  |  | 		for resp := range ch { | 
					
						
							| 
									
										
										
										
											2023-12-10 23:53:38 +08:00
										 |  |  | 			switch r := resp.(type) { | 
					
						
							|  |  |  | 			case api.ChatResponse: | 
					
						
							| 
									
										
										
										
											2023-12-19 03:23:38 +08:00
										 |  |  | 				sb.WriteString(r.Message.Content) | 
					
						
							| 
									
										
										
										
											2023-12-10 23:53:38 +08:00
										 |  |  | 				final = r | 
					
						
							|  |  |  | 			case gin.H: | 
					
						
							|  |  |  | 				if errorMsg, ok := r["error"].(string); ok { | 
					
						
							|  |  |  | 					c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg}) | 
					
						
							|  |  |  | 					return | 
					
						
							|  |  |  | 				} else { | 
					
						
							|  |  |  | 					c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in response"}) | 
					
						
							|  |  |  | 					return | 
					
						
							|  |  |  | 				} | 
					
						
							|  |  |  | 			default: | 
					
						
							|  |  |  | 				c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error"}) | 
					
						
							|  |  |  | 				return | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 			} | 
					
						
							|  |  |  | 		} | 
					
						
							| 
									
										
										
										
											2023-12-10 23:53:38 +08:00
										 |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-12-19 03:23:38 +08:00
										 |  |  | 		final.Message = api.Message{Role: "assistant", Content: sb.String()} | 
					
						
							| 
									
										
										
										
											2023-12-10 23:53:38 +08:00
										 |  |  | 		c.JSON(http.StatusOK, final) | 
					
						
							| 
									
										
										
										
											2023-12-06 03:57:33 +08:00
										 |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 	streamResponse(c, ch) | 
					
						
							|  |  |  | } | 
					
						
							| 
									
										
										
										
											2024-05-04 07:25:57 +08:00
										 |  |  | 
 | 
					
						
							|  |  |  | func handleErrorResponse(c *gin.Context, err error) { | 
					
						
							|  |  |  | 	if errors.Is(err, context.Canceled) { | 
					
						
							|  |  |  | 		c.JSON(499, gin.H{"error": "request canceled"}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 	if errors.Is(err, ErrMaxQueue) { | 
					
						
							|  |  |  | 		c.JSON(http.StatusServiceUnavailable, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | 		return | 
					
						
							|  |  |  | 	} | 
					
						
							|  |  |  | 	c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | 
					
						
							|  |  |  | } |