ollama/server/routes.go

189 lines
3.8 KiB
Go
Raw Normal View History

package server
import (
2023-07-06 14:33:29 -04:00
"embed"
2023-07-06 13:40:11 -04:00
"encoding/json"
"errors"
"io"
"log"
2023-07-06 20:03:00 -04:00
"math"
"net"
"net/http"
"os"
2023-07-06 13:40:11 -04:00
"path"
"strings"
"text/template"
"github.com/gin-gonic/gin"
2023-07-06 13:40:11 -04:00
"github.com/lithammer/fuzzysearch/fuzzy"
2023-07-07 18:29:17 -04:00
"golang.org/x/sync/errgroup"
2023-07-03 16:32:48 -04:00
"github.com/jmorganca/ollama/api"
2023-07-06 13:40:11 -04:00
"github.com/jmorganca/ollama/llama"
)
2023-07-06 14:33:29 -04:00
//go:embed templates/*
var templatesFS embed.FS
var templates = template.Must(template.ParseFS(templatesFS, "templates/*.prompt"))
2023-07-06 13:40:11 -04:00
func cacheDir() string {
home, err := os.UserHomeDir()
if err != nil {
panic(err)
}
return path.Join(home, ".ollama")
}
2023-07-05 15:37:33 -04:00
func generate(c *gin.Context) {
2023-07-07 18:29:17 -04:00
req := api.GenerateRequest{
Options: api.DefaultOptions(),
}
2023-07-05 15:37:33 -04:00
if err := c.ShouldBindJSON(&req); err != nil {
2023-07-07 17:04:43 -04:00
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
2023-07-05 15:37:33 -04:00
return
}
if remoteModel, _ := getRemote(req.Model); remoteModel != nil {
2023-07-06 18:43:04 -04:00
req.Model = remoteModel.FullName()
}
if _, err := os.Stat(req.Model); err != nil {
if !errors.Is(err, os.ErrNotExist) {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
req.Model = path.Join(cacheDir(), "models", req.Model+".bin")
}
2023-07-06 18:43:04 -04:00
2023-07-07 18:29:17 -04:00
llm, err := llama.New(req.Model, req.Options)
2023-07-05 15:37:33 -04:00
if err != nil {
2023-07-07 18:29:17 -04:00
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
2023-07-05 15:37:33 -04:00
return
}
2023-07-07 18:29:17 -04:00
defer llm.Close()
2023-07-06 13:40:11 -04:00
templateNames := make([]string, 0, len(templates.Templates()))
for _, template := range templates.Templates() {
templateNames = append(templateNames, template.Name())
}
2023-07-06 20:03:00 -04:00
match, _ := matchRankOne(path.Base(req.Model), templateNames)
2023-07-06 13:40:11 -04:00
if template := templates.Lookup(match); template != nil {
var sb strings.Builder
if err := template.Execute(&sb, req); err != nil {
2023-07-07 17:04:43 -04:00
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
2023-07-06 13:40:11 -04:00
return
}
req.Prompt = sb.String()
}
2023-07-05 15:37:33 -04:00
ch := make(chan string)
2023-07-07 18:29:17 -04:00
g, _ := errgroup.WithContext(c.Request.Context())
g.Go(func() error {
2023-07-05 15:37:33 -04:00
defer close(ch)
2023-07-07 18:29:17 -04:00
return llm.Predict(req.Prompt, func(s string) {
ch <- s
})
})
2023-07-04 00:47:00 -04:00
2023-07-07 18:29:17 -04:00
g.Go(func() error {
c.Stream(func(w io.Writer) bool {
s, ok := <-ch
if !ok {
return false
}
2023-07-06 13:40:11 -04:00
2023-07-07 18:29:17 -04:00
bts, err := json.Marshal(api.GenerateResponse{Response: s})
if err != nil {
return false
}
2023-07-06 13:40:11 -04:00
2023-07-07 18:29:17 -04:00
bts = append(bts, '\n')
if _, err := w.Write(bts); err != nil {
return false
}
2023-07-06 13:40:11 -04:00
2023-07-07 18:29:17 -04:00
return true
})
2023-07-06 13:40:11 -04:00
2023-07-07 18:29:17 -04:00
return nil
})
2023-07-07 18:29:17 -04:00
if err := g.Wait(); err != nil && !errors.Is(err, io.EOF) {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
2023-07-05 15:37:33 -04:00
}
func Serve(ln net.Listener) error {
r := gin.Default()
2023-07-07 23:46:15 -04:00
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Ollama is running")
})
2023-07-06 12:24:49 -04:00
r.POST("api/pull", func(c *gin.Context) {
var req api.PullRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
2023-07-06 12:24:49 -04:00
return
}
2023-07-06 14:18:40 -04:00
progressCh := make(chan api.PullProgress)
2023-07-06 12:24:49 -04:00
go func() {
defer close(progressCh)
if err := pull(req.Model, progressCh); err != nil {
var opError *net.OpError
if errors.As(err, &opError) {
c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
2023-07-06 12:24:49 -04:00
return
}
}()
c.Stream(func(w io.Writer) bool {
progress, ok := <-progressCh
if !ok {
return false
}
2023-07-06 15:30:36 -04:00
bts, err := json.Marshal(progress)
if err != nil {
return false
}
bts = append(bts, '\n')
if _, err := w.Write(bts); err != nil {
return false
}
2023-07-06 12:24:49 -04:00
return true
})
})
2023-07-05 15:37:33 -04:00
r.POST("/api/generate", generate)
log.Printf("Listening on %s", ln.Addr())
s := &http.Server{
Handler: r,
}
return s.Serve(ln)
}
2023-07-06 13:40:11 -04:00
func matchRankOne(source string, targets []string) (bestMatch string, bestRank int) {
2023-07-06 20:03:00 -04:00
bestRank = math.MaxInt
2023-07-06 13:40:11 -04:00
for _, target := range targets {
2023-07-06 20:03:00 -04:00
if rank := fuzzy.LevenshteinDistance(source, target); bestRank > rank {
2023-07-06 13:40:11 -04:00
bestRank = rank
bestMatch = target
}
}
return
}