routes.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. package server
  2. import (
  3. "embed"
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "log"
  8. "math"
  9. "net"
  10. "net/http"
  11. "os"
  12. "path"
  13. "strings"
  14. "text/template"
  15. "github.com/gin-gonic/gin"
  16. "github.com/lithammer/fuzzysearch/fuzzy"
  17. "golang.org/x/sync/errgroup"
  18. "github.com/jmorganca/ollama/api"
  19. "github.com/jmorganca/ollama/llama"
  20. )
  21. //go:embed templates/*
  22. var templatesFS embed.FS
  23. var templates = template.Must(template.ParseFS(templatesFS, "templates/*.prompt"))
  24. func cacheDir() string {
  25. home, err := os.UserHomeDir()
  26. if err != nil {
  27. panic(err)
  28. }
  29. return path.Join(home, ".ollama")
  30. }
  31. func generate(c *gin.Context) {
  32. req := api.GenerateRequest{
  33. Options: api.DefaultOptions(),
  34. }
  35. if err := c.ShouldBindJSON(&req); err != nil {
  36. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  37. return
  38. }
  39. if remoteModel, _ := getRemote(req.Model); remoteModel != nil {
  40. req.Model = remoteModel.FullName()
  41. }
  42. if _, err := os.Stat(req.Model); err != nil {
  43. if !errors.Is(err, os.ErrNotExist) {
  44. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  45. return
  46. }
  47. req.Model = path.Join(cacheDir(), "models", req.Model+".bin")
  48. }
  49. llm, err := llama.New(req.Model, req.Options)
  50. if err != nil {
  51. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  52. return
  53. }
  54. defer llm.Close()
  55. templateNames := make([]string, 0, len(templates.Templates()))
  56. for _, template := range templates.Templates() {
  57. templateNames = append(templateNames, template.Name())
  58. }
  59. match, _ := matchRankOne(path.Base(req.Model), templateNames)
  60. if template := templates.Lookup(match); template != nil {
  61. var sb strings.Builder
  62. if err := template.Execute(&sb, req); err != nil {
  63. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  64. return
  65. }
  66. req.Prompt = sb.String()
  67. }
  68. ch := make(chan any)
  69. g, _ := errgroup.WithContext(c.Request.Context())
  70. g.Go(func() error {
  71. defer close(ch)
  72. return llm.Predict(req.Prompt, func(s string) {
  73. ch <- api.GenerateResponse{Response: s}
  74. })
  75. })
  76. g.Go(func() error {
  77. stream(c, ch)
  78. return nil
  79. })
  80. if err := g.Wait(); err != nil && !errors.Is(err, io.EOF) {
  81. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  82. return
  83. }
  84. }
  85. func pull(c *gin.Context) {
  86. var req api.PullRequest
  87. if err := c.ShouldBindJSON(&req); err != nil {
  88. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  89. return
  90. }
  91. remote, err := getRemote(req.Model)
  92. if err != nil {
  93. c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
  94. return
  95. }
  96. ch := make(chan any)
  97. g, _ := errgroup.WithContext(c.Request.Context())
  98. g.Go(func() error {
  99. defer close(ch)
  100. return saveModel(remote, func(total, completed int64) {
  101. ch <- api.PullProgress{
  102. Total: total,
  103. Completed: completed,
  104. Percent: float64(total) / float64(completed) * 100,
  105. }
  106. })
  107. })
  108. g.Go(func() error {
  109. stream(c, ch)
  110. return nil
  111. })
  112. if err := g.Wait(); err != nil && !errors.Is(err, io.EOF) {
  113. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  114. return
  115. }
  116. }
  117. func Serve(ln net.Listener) error {
  118. r := gin.Default()
  119. r.GET("/", func(c *gin.Context) {
  120. c.String(http.StatusOK, "Ollama is running")
  121. })
  122. r.POST("api/pull", pull)
  123. r.POST("/api/generate", generate)
  124. log.Printf("Listening on %s", ln.Addr())
  125. s := &http.Server{
  126. Handler: r,
  127. }
  128. return s.Serve(ln)
  129. }
  130. func matchRankOne(source string, targets []string) (bestMatch string, bestRank int) {
  131. bestRank = math.MaxInt
  132. for _, target := range targets {
  133. if rank := fuzzy.LevenshteinDistance(source, target); bestRank > rank {
  134. bestRank = rank
  135. bestMatch = target
  136. }
  137. }
  138. return
  139. }
  140. func stream(c *gin.Context, ch chan any) {
  141. c.Stream(func(w io.Writer) bool {
  142. val, ok := <-ch
  143. if !ok {
  144. return false
  145. }
  146. bts, err := json.Marshal(val)
  147. if err != nil {
  148. return false
  149. }
  150. bts = append(bts, '\n')
  151. if _, err := w.Write(bts); err != nil {
  152. return false
  153. }
  154. return true
  155. })
  156. }