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 string)
  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 <- s
  74. })
  75. })
  76. g.Go(func() error {
  77. c.Stream(func(w io.Writer) bool {
  78. s, ok := <-ch
  79. if !ok {
  80. return false
  81. }
  82. bts, err := json.Marshal(api.GenerateResponse{Response: s})
  83. if err != nil {
  84. return false
  85. }
  86. bts = append(bts, '\n')
  87. if _, err := w.Write(bts); err != nil {
  88. return false
  89. }
  90. return true
  91. })
  92. return nil
  93. })
  94. if err := g.Wait(); err != nil && !errors.Is(err, io.EOF) {
  95. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  96. return
  97. }
  98. }
  99. func Serve(ln net.Listener) error {
  100. r := gin.Default()
  101. r.GET("/", func(c *gin.Context) {
  102. c.String(http.StatusOK, "Ollama is running")
  103. })
  104. r.POST("api/pull", func(c *gin.Context) {
  105. var req api.PullRequest
  106. if err := c.ShouldBindJSON(&req); err != nil {
  107. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  108. return
  109. }
  110. progressCh := make(chan api.PullProgress)
  111. go func() {
  112. defer close(progressCh)
  113. if err := pull(req.Model, progressCh); err != nil {
  114. var opError *net.OpError
  115. if errors.As(err, &opError) {
  116. c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
  117. return
  118. }
  119. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  120. return
  121. }
  122. }()
  123. c.Stream(func(w io.Writer) bool {
  124. progress, ok := <-progressCh
  125. if !ok {
  126. return false
  127. }
  128. bts, err := json.Marshal(progress)
  129. if err != nil {
  130. return false
  131. }
  132. bts = append(bts, '\n')
  133. if _, err := w.Write(bts); err != nil {
  134. return false
  135. }
  136. return true
  137. })
  138. })
  139. r.POST("/api/generate", generate)
  140. log.Printf("Listening on %s", ln.Addr())
  141. s := &http.Server{
  142. Handler: r,
  143. }
  144. return s.Serve(ln)
  145. }
  146. func matchRankOne(source string, targets []string) (bestMatch string, bestRank int) {
  147. bestRank = math.MaxInt
  148. for _, target := range targets {
  149. if rank := fuzzy.LevenshteinDistance(source, target); bestRank > rank {
  150. bestRank = rank
  151. bestMatch = target
  152. }
  153. }
  154. return
  155. }