routes.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. log.Printf("llm.Predict failed with %s", err)
  107. ch <- gin.H{"error": err.Error()}
  108. }
  109. }()
  110. streamResponse(c, ch)
  111. }
  112. func PullModelHandler(c *gin.Context) {
  113. var req api.PullRequest
  114. if err := c.ShouldBindJSON(&req); err != nil {
  115. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  116. return
  117. }
  118. ch := make(chan any)
  119. go func() {
  120. defer close(ch)
  121. fn := func(r api.ProgressResponse) {
  122. ch <- r
  123. }
  124. regOpts := &RegistryOptions{
  125. Insecure: req.Insecure,
  126. Username: req.Username,
  127. Password: req.Password,
  128. }
  129. if err := PullModel(req.Name, regOpts, fn); err != nil {
  130. ch <- gin.H{"error": err.Error()}
  131. }
  132. }()
  133. streamResponse(c, ch)
  134. }
  135. func PushModelHandler(c *gin.Context) {
  136. var req api.PushRequest
  137. if err := c.ShouldBindJSON(&req); err != nil {
  138. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  139. return
  140. }
  141. ch := make(chan any)
  142. go func() {
  143. defer close(ch)
  144. fn := func(r api.ProgressResponse) {
  145. ch <- r
  146. }
  147. regOpts := &RegistryOptions{
  148. Insecure: req.Insecure,
  149. Username: req.Username,
  150. Password: req.Password,
  151. }
  152. if err := PushModel(req.Name, regOpts, fn); err != nil {
  153. ch <- gin.H{"error": err.Error()}
  154. }
  155. }()
  156. streamResponse(c, ch)
  157. }
  158. func CreateModelHandler(c *gin.Context) {
  159. var req api.CreateRequest
  160. if err := c.ShouldBindJSON(&req); err != nil {
  161. c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
  162. return
  163. }
  164. ch := make(chan any)
  165. go func() {
  166. defer close(ch)
  167. fn := func(resp api.ProgressResponse) {
  168. ch <- resp
  169. }
  170. if err := CreateModel(req.Name, req.Path, fn); err != nil {
  171. ch <- gin.H{"error": err.Error()}
  172. }
  173. }()
  174. streamResponse(c, ch)
  175. }
  176. func DeleteModelHandler(c *gin.Context) {
  177. var req api.DeleteRequest
  178. if err := c.ShouldBindJSON(&req); err != nil {
  179. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  180. return
  181. }
  182. if err := DeleteModel(req.Name); err != nil {
  183. if os.IsNotExist(err) {
  184. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  185. } else {
  186. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  187. }
  188. return
  189. }
  190. }
  191. func ListModelsHandler(c *gin.Context) {
  192. var models []api.ListResponseModel
  193. fp, err := GetManifestPath()
  194. if err != nil {
  195. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  196. return
  197. }
  198. err = filepath.Walk(fp, func(path string, info os.FileInfo, err error) error {
  199. if err != nil {
  200. if errors.Is(err, os.ErrNotExist) {
  201. log.Printf("manifest file does not exist: %s", fp)
  202. return nil
  203. }
  204. return err
  205. }
  206. if !info.IsDir() {
  207. fi, err := os.Stat(path)
  208. if err != nil {
  209. log.Printf("skipping file: %s", fp)
  210. return nil
  211. }
  212. path := path[len(fp)+1:]
  213. slashIndex := strings.LastIndex(path, "/")
  214. if slashIndex == -1 {
  215. return nil
  216. }
  217. tag := path[:slashIndex] + ":" + path[slashIndex+1:]
  218. mp := ParseModelPath(tag)
  219. manifest, err := GetManifest(mp)
  220. if err != nil {
  221. log.Printf("skipping file: %s", fp)
  222. return nil
  223. }
  224. model := api.ListResponseModel{
  225. Name: mp.GetShortTagname(),
  226. Size: manifest.GetTotalSize(),
  227. ModifiedAt: fi.ModTime(),
  228. }
  229. models = append(models, model)
  230. }
  231. return nil
  232. })
  233. if err != nil {
  234. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  235. return
  236. }
  237. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  238. }
  239. func CopyModelHandler(c *gin.Context) {
  240. var req api.CopyRequest
  241. if err := c.ShouldBindJSON(&req); err != nil {
  242. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  243. return
  244. }
  245. if err := CopyModel(req.Source, req.Destination); err != nil {
  246. if os.IsNotExist(err) {
  247. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  248. } else {
  249. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  250. }
  251. return
  252. }
  253. }
  254. func Serve(ln net.Listener) error {
  255. config := cors.DefaultConfig()
  256. config.AllowWildcard = true
  257. // only allow http/https from localhost
  258. config.AllowOrigins = []string{
  259. "http://localhost",
  260. "http://localhost:*",
  261. "https://localhost",
  262. "https://localhost:*",
  263. "http://127.0.0.1",
  264. "http://127.0.0.1:*",
  265. "https://127.0.0.1",
  266. "https://127.0.0.1:*",
  267. }
  268. r := gin.Default()
  269. r.Use(cors.New(config))
  270. r.GET("/", func(c *gin.Context) {
  271. c.String(http.StatusOK, "Ollama is running")
  272. })
  273. r.POST("/api/pull", PullModelHandler)
  274. r.POST("/api/generate", GenerateHandler)
  275. r.POST("/api/create", CreateModelHandler)
  276. r.POST("/api/push", PushModelHandler)
  277. r.POST("/api/copy", CopyModelHandler)
  278. r.GET("/api/tags", ListModelsHandler)
  279. r.DELETE("/api/delete", DeleteModelHandler)
  280. log.Printf("Listening on %s", ln.Addr())
  281. s := &http.Server{
  282. Handler: r,
  283. }
  284. return s.Serve(ln)
  285. }
  286. func streamResponse(c *gin.Context, ch chan any) {
  287. c.Stream(func(w io.Writer) bool {
  288. val, ok := <-ch
  289. if !ok {
  290. return false
  291. }
  292. bts, err := json.Marshal(val)
  293. if err != nil {
  294. log.Printf("streamResponse: json.Marshal failed with %s", err)
  295. return false
  296. }
  297. bts = append(bts, '\n')
  298. if _, err := w.Write(bts); err != nil {
  299. log.Printf("streamResponse: w.Write failed with %s", err)
  300. return false
  301. }
  302. return true
  303. })
  304. }