routes.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. package server
  2. import (
  3. "embed"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "log"
  8. "net"
  9. "net/http"
  10. "path"
  11. "runtime"
  12. "strings"
  13. "text/template"
  14. "github.com/gin-gonic/gin"
  15. "github.com/lithammer/fuzzysearch/fuzzy"
  16. "github.com/jmorganca/ollama/api"
  17. "github.com/jmorganca/ollama/llama"
  18. )
  19. //go:embed templates/*
  20. var templatesFS embed.FS
  21. var templates = template.Must(template.ParseFS(templatesFS, "templates/*.prompt"))
  22. func generate(c *gin.Context) {
  23. // TODO: these should be request parameters
  24. gpulayers := 1
  25. tokens := 512
  26. threads := runtime.NumCPU()
  27. var req api.GenerateRequest
  28. if err := c.ShouldBindJSON(&req); err != nil {
  29. c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
  30. return
  31. }
  32. model, err := llama.New(req.Model, llama.EnableF16Memory, llama.SetContext(128), llama.EnableEmbeddings, llama.SetGPULayers(gpulayers))
  33. if err != nil {
  34. fmt.Println("Loading the model failed:", err.Error())
  35. return
  36. }
  37. defer model.Free()
  38. templateNames := make([]string, 0, len(templates.Templates()))
  39. for _, template := range templates.Templates() {
  40. templateNames = append(templateNames, template.Name())
  41. }
  42. match, _ := matchRankOne(path.Base(req.Prompt), templateNames)
  43. if template := templates.Lookup(match); template != nil {
  44. var sb strings.Builder
  45. if err := template.Execute(&sb, req); err != nil {
  46. fmt.Println("Prompt template failed:", err.Error())
  47. return
  48. }
  49. req.Prompt = sb.String()
  50. }
  51. ch := make(chan string)
  52. go func() {
  53. defer close(ch)
  54. _, err := model.Predict(req.Prompt, llama.Debug, llama.SetTokenCallback(func(token string) bool {
  55. ch <- token
  56. return true
  57. }), llama.SetTokens(tokens), llama.SetThreads(threads), llama.SetTopK(90), llama.SetTopP(0.86), llama.SetStopWords("llama"))
  58. if err != nil {
  59. panic(err)
  60. }
  61. }()
  62. c.Stream(func(w io.Writer) bool {
  63. token, ok := <-ch
  64. if !ok {
  65. return false
  66. }
  67. resp := api.TokenResponse{
  68. Choices: []api.TokenResponseChoice{
  69. {
  70. Text: token,
  71. },
  72. },
  73. }
  74. bts, err := json.Marshal(resp)
  75. if err != nil {
  76. return false
  77. }
  78. bts = append(bts, '\n')
  79. if _, err := w.Write(bts); err != nil {
  80. return false
  81. }
  82. return true
  83. })
  84. }
  85. func Serve(ln net.Listener) error {
  86. r := gin.Default()
  87. r.POST("api/pull", func(c *gin.Context) {
  88. var req api.PullRequest
  89. if err := c.ShouldBindJSON(&req); err != nil {
  90. c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
  91. return
  92. }
  93. progressCh := make(chan api.PullProgress)
  94. go func() {
  95. defer close(progressCh)
  96. if err := pull(req.Model, progressCh); err != nil {
  97. c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
  98. return
  99. }
  100. }()
  101. c.Stream(func(w io.Writer) bool {
  102. progress, ok := <-progressCh
  103. if !ok {
  104. return false
  105. }
  106. c.SSEvent("progress", progress)
  107. return true
  108. })
  109. })
  110. r.POST("/api/generate", generate)
  111. log.Printf("Listening on %s", ln.Addr())
  112. s := &http.Server{
  113. Handler: r,
  114. }
  115. return s.Serve(ln)
  116. }
  117. func matchRankOne(source string, targets []string) (bestMatch string, bestRank int) {
  118. for _, target := range targets {
  119. if rank := fuzzy.LevenshteinDistance(source, target); bestRank < rank {
  120. bestRank = rank
  121. bestMatch = target
  122. }
  123. }
  124. return
  125. }