ollama/server/routes.go

367 lines
7.7 KiB
Go
Raw Normal View History

package server
import (
2023-07-06 17:40:11 +00:00
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
2023-07-15 00:27:14 +00:00
"path/filepath"
2023-08-01 01:35:18 +00:00
"reflect"
2023-07-06 17:40:11 +00:00
"strings"
2023-07-18 18:59:42 +00:00
"sync"
2023-07-13 01:18:06 +00:00
"time"
2023-07-22 01:01:24 +00:00
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
2023-07-03 20:32:48 +00:00
"github.com/jmorganca/ollama/api"
2023-07-06 17:40:11 +00:00
"github.com/jmorganca/ollama/llama"
)
2023-08-01 01:35:18 +00:00
var loaded struct {
2023-07-19 22:00:28 +00:00
mu sync.Mutex
llm *llama.LLM
expireAt time.Time
expireTimer *time.Timer
2023-08-01 01:35:18 +00:00
digest string
options api.Options
2023-07-18 18:59:42 +00:00
}
2023-07-20 23:09:23 +00:00
func GenerateHandler(c *gin.Context) {
2023-08-01 01:35:18 +00:00
loaded.mu.Lock()
defer loaded.mu.Unlock()
2023-07-18 18:59:42 +00:00
2023-07-18 19:02:02 +00:00
checkpointStart := time.Now()
2023-07-13 01:18:06 +00:00
2023-07-17 19:08:10 +00:00
var req api.GenerateRequest
2023-07-05 19:37:33 +00:00
if err := c.ShouldBindJSON(&req); err != nil {
2023-07-07 21:04:43 +00:00
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
2023-07-05 19:37:33 +00:00
return
}
model, err := GetModel(req.Model)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
2023-07-06 22:43:04 +00:00
2023-08-03 19:55:35 +00:00
opts := api.DefaultOptions()
if err := opts.FromMap(model.Options); err != nil {
log.Printf("could not load model options: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if err := opts.FromMap(req.Options); err != nil {
log.Printf("could not merge model options: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if model.Digest != loaded.digest || !reflect.DeepEqual(loaded.options, opts) {
2023-08-01 01:35:18 +00:00
if loaded.llm != nil {
loaded.llm.Close()
loaded.llm = nil
loaded.digest = ""
2023-07-18 18:59:42 +00:00
}
2023-07-17 19:08:10 +00:00
2023-07-18 18:59:42 +00:00
llm, err := llama.New(model.ModelPath, opts)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
2023-08-01 01:35:18 +00:00
loaded.llm = llm
loaded.digest = model.Digest
2023-08-03 19:55:35 +00:00
loaded.options = opts
2023-07-19 22:00:28 +00:00
}
2023-08-01 01:35:18 +00:00
sessionDuration := 5 * time.Minute
2023-07-19 22:00:28 +00:00
2023-08-01 01:35:18 +00:00
loaded.expireAt = time.Now().Add(sessionDuration)
if loaded.expireTimer == nil {
loaded.expireTimer = time.AfterFunc(sessionDuration, func() {
loaded.mu.Lock()
defer loaded.mu.Unlock()
2023-07-19 22:00:28 +00:00
2023-08-01 01:35:18 +00:00
if time.Now().Before(loaded.expireAt) {
2023-07-19 22:00:28 +00:00
return
}
2023-08-01 01:35:18 +00:00
if loaded.llm == nil {
2023-07-19 22:00:28 +00:00
return
}
2023-08-01 01:35:18 +00:00
loaded.llm.Close()
loaded.llm = nil
loaded.digest = ""
2023-07-19 22:00:28 +00:00
})
2023-07-06 17:40:11 +00:00
}
2023-08-01 01:35:18 +00:00
loaded.expireTimer.Reset(sessionDuration)
2023-07-06 17:40:11 +00:00
2023-07-18 19:02:02 +00:00
checkpointLoaded := time.Now()
2023-07-18 18:59:42 +00:00
prompt, err := model.Prompt(req)
2023-07-11 21:57:17 +00:00
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
2023-07-04 04:47:00 +00:00
ch := make(chan any)
go func() {
defer close(ch)
2023-07-20 19:12:08 +00:00
fn := func(r api.GenerateResponse) {
2023-08-01 01:35:18 +00:00
loaded.expireAt = time.Now().Add(sessionDuration)
loaded.expireTimer.Reset(sessionDuration)
2023-07-19 22:00:28 +00:00
r.Model = req.Model
r.CreatedAt = time.Now().UTC()
if r.Done {
2023-07-18 19:02:02 +00:00
r.TotalDuration = time.Since(checkpointStart)
r.LoadDuration = checkpointLoaded.Sub(checkpointStart)
}
ch <- r
2023-07-20 19:12:08 +00:00
}
2023-08-01 01:35:18 +00:00
if err := loaded.llm.Predict(req.Context, prompt, fn); err != nil {
2023-07-20 19:12:08 +00:00
ch <- gin.H{"error": err.Error()}
}
}()
2023-07-11 21:57:17 +00:00
streamResponse(c, ch)
2023-07-11 18:54:22 +00:00
}
2023-07-06 17:40:11 +00:00
2023-07-20 23:09:23 +00:00
func PullModelHandler(c *gin.Context) {
2023-07-11 18:54:22 +00:00
var req api.PullRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
ch := make(chan any)
go func() {
defer close(ch)
2023-07-19 01:51:30 +00:00
fn := func(r api.ProgressResponse) {
ch <- r
}
2023-07-19 01:51:30 +00:00
regOpts := &RegistryOptions{
Insecure: req.Insecure,
Username: req.Username,
Password: req.Password,
}
if err := PullModel(req.Name, regOpts, fn); err != nil {
2023-07-20 19:12:08 +00:00
ch <- gin.H{"error": err.Error()}
}
}()
streamResponse(c, ch)
}
2023-07-20 23:09:23 +00:00
func PushModelHandler(c *gin.Context) {
var req api.PushRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
2023-07-11 18:54:22 +00:00
return
}
2023-07-06 17:40:11 +00:00
ch := make(chan any)
go func() {
defer close(ch)
2023-07-19 01:51:30 +00:00
fn := func(r api.ProgressResponse) {
ch <- r
}
2023-07-19 01:51:30 +00:00
regOpts := &RegistryOptions{
Insecure: req.Insecure,
Username: req.Username,
Password: req.Password,
}
if err := PushModel(req.Name, regOpts, fn); err != nil {
2023-07-20 19:12:08 +00:00
ch <- gin.H{"error": err.Error()}
}
}()
streamResponse(c, ch)
}
2023-07-20 23:09:23 +00:00
func CreateModelHandler(c *gin.Context) {
var req api.CreateRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
2023-07-13 02:07:15 +00:00
return
}
2023-07-11 18:54:22 +00:00
ch := make(chan any)
go func() {
defer close(ch)
fn := func(resp api.ProgressResponse) {
ch <- resp
}
if err := CreateModel(req.Name, req.Path, fn); err != nil {
2023-07-20 19:12:08 +00:00
ch <- gin.H{"error": err.Error()}
}
}()
2023-07-07 22:29:17 +00:00
streamResponse(c, ch)
2023-07-05 19:37:33 +00:00
}
2023-07-20 23:09:23 +00:00
func DeleteModelHandler(c *gin.Context) {
var req api.DeleteRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := DeleteModel(req.Name); err != nil {
if os.IsNotExist(err) {
c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
} else {
2023-07-20 23:09:23 +00:00
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
return
}
2023-07-20 23:09:23 +00:00
}
func ListModelsHandler(c *gin.Context) {
2023-07-18 16:09:45 +00:00
var models []api.ListResponseModel
fp, err := GetManifestPath()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
err = filepath.Walk(fp, func(path string, info os.FileInfo, err error) error {
if err != nil {
if errors.Is(err, os.ErrNotExist) {
log.Printf("manifest file does not exist: %s", fp)
return nil
}
2023-07-18 16:09:45 +00:00
return err
}
if !info.IsDir() {
fi, err := os.Stat(path)
if err != nil {
log.Printf("skipping file: %s", fp)
return nil
2023-07-18 16:09:45 +00:00
}
path := path[len(fp)+1:]
slashIndex := strings.LastIndex(path, "/")
if slashIndex == -1 {
return nil
}
tag := path[:slashIndex] + ":" + path[slashIndex+1:]
mp := ParseModelPath(tag)
manifest, err := GetManifest(mp)
if err != nil {
log.Printf("skipping file: %s", fp)
return nil
2023-07-18 16:09:45 +00:00
}
model := api.ListResponseModel{
Name: mp.GetShortTagname(),
Size: manifest.GetTotalSize(),
ModifiedAt: fi.ModTime(),
}
models = append(models, model)
}
return nil
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
2023-07-19 22:00:28 +00:00
c.JSON(http.StatusOK, api.ListResponse{Models: models})
2023-07-18 16:09:45 +00:00
}
2023-07-24 15:27:28 +00:00
func CopyModelHandler(c *gin.Context) {
var req api.CopyRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := CopyModel(req.Source, req.Destination); err != nil {
if os.IsNotExist(err) {
c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
} else {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
return
}
}
2023-07-05 19:37:33 +00:00
func Serve(ln net.Listener) error {
2023-07-22 01:01:24 +00:00
config := cors.DefaultConfig()
config.AllowWildcard = true
// only allow http/https from localhost
config.AllowOrigins = []string{
"http://localhost",
"http://localhost:*",
"https://localhost",
"https://localhost:*",
"http://127.0.0.1",
"http://127.0.0.1:*",
"https://127.0.0.1",
"https://127.0.0.1:*",
}
2023-07-05 19:37:33 +00:00
r := gin.Default()
2023-07-22 01:01:24 +00:00
r.Use(cors.New(config))
2023-07-05 19:37:33 +00:00
2023-07-08 03:46:15 +00:00
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Ollama is running")
})
2023-08-01 18:50:38 +00:00
r.HEAD("/", func(c *gin.Context) {
c.Status(http.StatusOK)
})
2023-07-08 03:46:15 +00:00
2023-07-20 23:09:23 +00:00
r.POST("/api/pull", PullModelHandler)
r.POST("/api/generate", GenerateHandler)
r.POST("/api/create", CreateModelHandler)
r.POST("/api/push", PushModelHandler)
2023-07-24 15:27:28 +00:00
r.POST("/api/copy", CopyModelHandler)
2023-07-20 23:09:23 +00:00
r.GET("/api/tags", ListModelsHandler)
r.DELETE("/api/delete", DeleteModelHandler)
log.Printf("Listening on %s", ln.Addr())
s := &http.Server{
Handler: r,
}
return s.Serve(ln)
}
2023-07-06 17:40:11 +00:00
func streamResponse(c *gin.Context, ch chan any) {
2023-07-11 18:54:22 +00:00
c.Stream(func(w io.Writer) bool {
val, ok := <-ch
if !ok {
return false
}
bts, err := json.Marshal(val)
if err != nil {
2023-07-31 20:46:37 +00:00
log.Printf("streamResponse: json.Marshal failed with %s", err)
2023-07-11 18:54:22 +00:00
return false
}
bts = append(bts, '\n')
if _, err := w.Write(bts); err != nil {
2023-07-31 20:46:37 +00:00
log.Printf("streamResponse: w.Write failed with %s", err)
2023-07-11 18:54:22 +00:00
return false
}
return true
})
}