routes.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. package server
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "log"
  8. "net"
  9. "net/http"
  10. "os"
  11. "path/filepath"
  12. "strings"
  13. "sync"
  14. "time"
  15. "dario.cat/mergo"
  16. "github.com/gin-contrib/cors"
  17. "github.com/gin-gonic/gin"
  18. "github.com/jmorganca/ollama/api"
  19. "github.com/jmorganca/ollama/llama"
  20. )
  21. var activeSession struct {
  22. mu sync.Mutex
  23. id int64
  24. llm *llama.LLM
  25. expireAt time.Time
  26. expireTimer *time.Timer
  27. }
  28. func GenerateHandler(c *gin.Context) {
  29. activeSession.mu.Lock()
  30. defer activeSession.mu.Unlock()
  31. checkpointStart := time.Now()
  32. var req api.GenerateRequest
  33. if err := c.ShouldBindJSON(&req); err != nil {
  34. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  35. return
  36. }
  37. model, err := GetModel(req.Model)
  38. if err != nil {
  39. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  40. return
  41. }
  42. if req.SessionID == 0 || req.SessionID != activeSession.id {
  43. if activeSession.llm != nil {
  44. activeSession.llm.Close()
  45. activeSession.llm = nil
  46. }
  47. opts := api.DefaultOptions()
  48. if err := mergo.Merge(&opts, model.Options, mergo.WithOverride); err != nil {
  49. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  50. return
  51. }
  52. if err := mergo.Merge(&opts, req.Options, mergo.WithOverride); err != nil {
  53. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  54. return
  55. }
  56. llm, err := llama.New(model.ModelPath, opts)
  57. if err != nil {
  58. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  59. return
  60. }
  61. activeSession.id = time.Now().UnixNano()
  62. activeSession.llm = llm
  63. }
  64. sessionDuration := req.SessionDuration
  65. sessionID := activeSession.id
  66. activeSession.expireAt = time.Now().Add(sessionDuration.Duration)
  67. if activeSession.expireTimer == nil {
  68. activeSession.expireTimer = time.AfterFunc(sessionDuration.Duration, func() {
  69. activeSession.mu.Lock()
  70. defer activeSession.mu.Unlock()
  71. if sessionID != activeSession.id {
  72. return
  73. }
  74. if time.Now().Before(activeSession.expireAt) {
  75. return
  76. }
  77. activeSession.llm.Close()
  78. activeSession.llm = nil
  79. activeSession.id = 0
  80. })
  81. }
  82. activeSession.expireTimer.Reset(sessionDuration.Duration)
  83. checkpointLoaded := time.Now()
  84. prompt, err := model.Prompt(req)
  85. if err != nil {
  86. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  87. return
  88. }
  89. ch := make(chan any)
  90. go func() {
  91. defer close(ch)
  92. fn := func(r api.GenerateResponse) {
  93. activeSession.expireAt = time.Now().Add(sessionDuration.Duration)
  94. activeSession.expireTimer.Reset(sessionDuration.Duration)
  95. r.Model = req.Model
  96. r.CreatedAt = time.Now().UTC()
  97. r.SessionID = activeSession.id
  98. r.SessionExpiresAt = activeSession.expireAt.UTC()
  99. if r.Done {
  100. r.TotalDuration = time.Since(checkpointStart)
  101. r.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  102. }
  103. ch <- r
  104. }
  105. if err := activeSession.llm.Predict(req.Context, prompt, fn); err != nil {
  106. ch <- gin.H{"error": err.Error()}
  107. }
  108. }()
  109. streamResponse(c, ch)
  110. }
  111. func PullModelHandler(c *gin.Context) {
  112. var req api.PullRequest
  113. if err := c.ShouldBindJSON(&req); err != nil {
  114. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  115. return
  116. }
  117. ch := make(chan any)
  118. go func() {
  119. defer close(ch)
  120. fn := func(r api.ProgressResponse) {
  121. ch <- r
  122. }
  123. regOpts := &RegistryOptions{
  124. Insecure: req.Insecure,
  125. Username: req.Username,
  126. Password: req.Password,
  127. }
  128. if err := PullModel(req.Name, regOpts, fn); err != nil {
  129. ch <- gin.H{"error": err.Error()}
  130. }
  131. }()
  132. streamResponse(c, ch)
  133. }
  134. func PushModelHandler(c *gin.Context) {
  135. var req api.PushRequest
  136. if err := c.ShouldBindJSON(&req); err != nil {
  137. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  138. return
  139. }
  140. ch := make(chan any)
  141. go func() {
  142. defer close(ch)
  143. fn := func(r api.ProgressResponse) {
  144. ch <- r
  145. }
  146. regOpts := &RegistryOptions{
  147. Insecure: req.Insecure,
  148. Username: req.Username,
  149. Password: req.Password,
  150. }
  151. if err := PushModel(req.Name, regOpts, fn); err != nil {
  152. ch <- gin.H{"error": err.Error()}
  153. }
  154. }()
  155. streamResponse(c, ch)
  156. }
  157. func CreateModelHandler(c *gin.Context) {
  158. var req api.CreateRequest
  159. if err := c.ShouldBindJSON(&req); err != nil {
  160. c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
  161. return
  162. }
  163. ch := make(chan any)
  164. go func() {
  165. defer close(ch)
  166. fn := func(resp api.ProgressResponse) {
  167. ch <- resp
  168. }
  169. if err := CreateModel(req.Name, req.Path, fn); err != nil {
  170. ch <- gin.H{"error": err.Error()}
  171. }
  172. }()
  173. streamResponse(c, ch)
  174. }
  175. func DeleteModelHandler(c *gin.Context) {
  176. var req api.DeleteRequest
  177. if err := c.ShouldBindJSON(&req); err != nil {
  178. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  179. return
  180. }
  181. if err := DeleteModel(req.Name); err != nil {
  182. if os.IsNotExist(err) {
  183. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  184. } else {
  185. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  186. }
  187. return
  188. }
  189. }
  190. func ListModelsHandler(c *gin.Context) {
  191. var models []api.ListResponseModel
  192. fp, err := GetManifestPath()
  193. if err != nil {
  194. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  195. return
  196. }
  197. err = filepath.Walk(fp, func(path string, info os.FileInfo, err error) error {
  198. if err != nil {
  199. if errors.Is(err, os.ErrNotExist) {
  200. log.Printf("manifest file does not exist: %s", fp)
  201. return nil
  202. }
  203. return err
  204. }
  205. if !info.IsDir() {
  206. fi, err := os.Stat(path)
  207. if err != nil {
  208. log.Printf("skipping file: %s", fp)
  209. return nil
  210. }
  211. path := path[len(fp)+1:]
  212. slashIndex := strings.LastIndex(path, "/")
  213. if slashIndex == -1 {
  214. return nil
  215. }
  216. tag := path[:slashIndex] + ":" + path[slashIndex+1:]
  217. mp := ParseModelPath(tag)
  218. manifest, err := GetManifest(mp)
  219. if err != nil {
  220. log.Printf("skipping file: %s", fp)
  221. return nil
  222. }
  223. model := api.ListResponseModel{
  224. Name: mp.GetShortTagname(),
  225. Size: manifest.GetTotalSize(),
  226. ModifiedAt: fi.ModTime(),
  227. }
  228. models = append(models, model)
  229. }
  230. return nil
  231. })
  232. if err != nil {
  233. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  234. return
  235. }
  236. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  237. }
  238. func CopyModelHandler(c *gin.Context) {
  239. var req api.CopyRequest
  240. if err := c.ShouldBindJSON(&req); err != nil {
  241. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  242. return
  243. }
  244. if err := CopyModel(req.Source, req.Destination); err != nil {
  245. if os.IsNotExist(err) {
  246. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  247. } else {
  248. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  249. }
  250. return
  251. }
  252. }
  253. func Serve(ln net.Listener) error {
  254. config := cors.DefaultConfig()
  255. config.AllowWildcard = true
  256. // only allow http/https from localhost
  257. config.AllowOrigins = []string{
  258. "http://localhost",
  259. "http://localhost:*",
  260. "https://localhost",
  261. "https://localhost:*",
  262. "http://127.0.0.1",
  263. "http://127.0.0.1:*",
  264. "https://127.0.0.1",
  265. "https://127.0.0.1:*",
  266. }
  267. r := gin.Default()
  268. r.Use(cors.New(config))
  269. r.GET("/", func(c *gin.Context) {
  270. c.String(http.StatusOK, "Ollama is running")
  271. })
  272. r.POST("/api/pull", PullModelHandler)
  273. r.POST("/api/generate", GenerateHandler)
  274. r.POST("/api/create", CreateModelHandler)
  275. r.POST("/api/push", PushModelHandler)
  276. r.POST("/api/copy", CopyModelHandler)
  277. r.GET("/api/tags", ListModelsHandler)
  278. r.DELETE("/api/delete", DeleteModelHandler)
  279. log.Printf("Listening on %s", ln.Addr())
  280. s := &http.Server{
  281. Handler: r,
  282. }
  283. return s.Serve(ln)
  284. }
  285. func streamResponse(c *gin.Context, ch chan any) {
  286. c.Stream(func(w io.Writer) bool {
  287. val, ok := <-ch
  288. if !ok {
  289. return false
  290. }
  291. bts, err := json.Marshal(val)
  292. if err != nil {
  293. return false
  294. }
  295. bts = append(bts, '\n')
  296. if _, err := w.Write(bts); err != nil {
  297. return false
  298. }
  299. return true
  300. })
  301. }