ollama/server/routes.go

359 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-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-17 19:08:10 +00:00
"dario.cat/mergo"
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-07-18 18:59:42 +00:00
var activeSession struct {
2023-07-19 22:00:28 +00:00
mu sync.Mutex
id int64
llm *llama.LLM
expireAt time.Time
expireTimer *time.Timer
2023-07-18 18:59:42 +00:00
}
2023-07-20 23:09:23 +00:00
func GenerateHandler(c *gin.Context) {
2023-07-19 22:00:28 +00:00
activeSession.mu.Lock()
defer activeSession.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-07-19 22:00:28 +00:00
if req.SessionID == 0 || req.SessionID != activeSession.id {
if activeSession.llm != nil {
activeSession.llm.Close()
activeSession.llm = nil
2023-07-18 18:59:42 +00:00
}
2023-07-17 19:08:10 +00:00
2023-07-18 18:59:42 +00:00
opts := api.DefaultOptions()
if err := mergo.Merge(&opts, model.Options, mergo.WithOverride); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
2023-07-17 19:08:10 +00:00
2023-07-18 18:59:42 +00:00
if err := mergo.Merge(&opts, req.Options, mergo.WithOverride); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
llm, err := llama.New(model.ModelPath, opts)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
2023-07-19 22:00:28 +00:00
activeSession.id = time.Now().UnixNano()
activeSession.llm = llm
}
sessionDuration := req.SessionDuration
sessionID := activeSession.id
activeSession.expireAt = time.Now().Add(sessionDuration.Duration)
if activeSession.expireTimer == nil {
activeSession.expireTimer = time.AfterFunc(sessionDuration.Duration, func() {
activeSession.mu.Lock()
defer activeSession.mu.Unlock()
if sessionID != activeSession.id {
return
}
if time.Now().Before(activeSession.expireAt) {
return
}
activeSession.llm.Close()
activeSession.llm = nil
activeSession.id = 0
})
2023-07-06 17:40:11 +00:00
}
2023-07-19 22:00:28 +00:00
activeSession.expireTimer.Reset(sessionDuration.Duration)
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-07-19 22:00:28 +00:00
activeSession.expireAt = time.Now().Add(sessionDuration.Duration)
activeSession.expireTimer.Reset(sessionDuration.Duration)
r.Model = req.Model
r.CreatedAt = time.Now().UTC()
2023-07-19 22:00:28 +00:00
r.SessionID = activeSession.id
r.SessionExpiresAt = activeSession.expireAt.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-07-19 22:00:28 +00:00
if err := activeSession.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-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 {
return false
}
bts = append(bts, '\n')
if _, err := w.Write(bts); err != nil {
return false
}
return true
})
}