routes.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. package server
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "log"
  9. "net"
  10. "net/http"
  11. "os"
  12. "path/filepath"
  13. "reflect"
  14. "strings"
  15. "sync"
  16. "time"
  17. "github.com/gin-contrib/cors"
  18. "github.com/gin-gonic/gin"
  19. "gonum.org/v1/gonum/mat"
  20. "github.com/jmorganca/ollama/api"
  21. "github.com/jmorganca/ollama/llm"
  22. "github.com/jmorganca/ollama/vector"
  23. )
  24. var loaded struct {
  25. mu sync.Mutex
  26. llm llm.LLM
  27. Embeddings []vector.Embedding
  28. expireAt time.Time
  29. expireTimer *time.Timer
  30. digest string
  31. options api.Options
  32. }
  33. var defaultSessionDuration = 5 * time.Minute
  34. // load a model into memory if it is not already loaded, it is up to the caller to lock loaded.mu before calling this function
  35. func load(model *Model, reqOpts map[string]interface{}, sessionDuration time.Duration) error {
  36. opts := api.DefaultOptions()
  37. if err := opts.FromMap(model.Options); err != nil {
  38. log.Printf("could not load model options: %v", err)
  39. return err
  40. }
  41. if err := opts.FromMap(reqOpts); err != nil {
  42. log.Printf("could not merge model options: %v", err)
  43. return err
  44. }
  45. if model.Digest != loaded.digest || !reflect.DeepEqual(loaded.options, opts) {
  46. if loaded.llm != nil {
  47. loaded.llm.Close()
  48. loaded.llm = nil
  49. loaded.digest = ""
  50. }
  51. if model.Embeddings != nil && len(model.Embeddings) > 0 {
  52. opts.EmbeddingOnly = true // this is requried to generate embeddings, completions will still work
  53. loaded.Embeddings = model.Embeddings
  54. }
  55. llmModel, err := llm.New(model.ModelPath, model.AdapterPaths, opts)
  56. if err != nil {
  57. return err
  58. }
  59. // set cache values before modifying opts
  60. loaded.llm = llmModel
  61. loaded.digest = model.Digest
  62. loaded.options = opts
  63. if opts.NumKeep < 0 {
  64. promptWithSystem, err := model.Prompt(api.GenerateRequest{}, "")
  65. if err != nil {
  66. return err
  67. }
  68. promptNoSystem, err := model.Prompt(api.GenerateRequest{Context: []int{0}}, "")
  69. if err != nil {
  70. return err
  71. }
  72. tokensWithSystem := llmModel.Encode(promptWithSystem)
  73. tokensNoSystem := llmModel.Encode(promptNoSystem)
  74. opts.NumKeep = len(tokensWithSystem) - len(tokensNoSystem) + 1
  75. llmModel.SetOptions(opts)
  76. }
  77. }
  78. loaded.expireAt = time.Now().Add(sessionDuration)
  79. if loaded.expireTimer == nil {
  80. loaded.expireTimer = time.AfterFunc(sessionDuration, func() {
  81. loaded.mu.Lock()
  82. defer loaded.mu.Unlock()
  83. if time.Now().Before(loaded.expireAt) {
  84. return
  85. }
  86. if loaded.llm == nil {
  87. return
  88. }
  89. loaded.llm.Close()
  90. loaded.llm = nil
  91. loaded.digest = ""
  92. })
  93. }
  94. loaded.expireTimer.Reset(sessionDuration)
  95. return nil
  96. }
  97. func GenerateHandler(c *gin.Context) {
  98. loaded.mu.Lock()
  99. defer loaded.mu.Unlock()
  100. checkpointStart := time.Now()
  101. var req api.GenerateRequest
  102. if err := c.ShouldBindJSON(&req); err != nil {
  103. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  104. return
  105. }
  106. model, err := GetModel(req.Model)
  107. if err != nil {
  108. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  109. return
  110. }
  111. sessionDuration := defaultSessionDuration // TODO: set this duration from the request if specified
  112. if err := load(model, req.Options, sessionDuration); err != nil {
  113. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  114. return
  115. }
  116. checkpointLoaded := time.Now()
  117. embedding := ""
  118. if model.Embeddings != nil && len(model.Embeddings) > 0 {
  119. promptEmbed, err := loaded.llm.Embedding(req.Prompt)
  120. if err != nil {
  121. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  122. return
  123. }
  124. // TODO: set embed_top from specified parameters in modelfile
  125. embed_top := 3
  126. topK := vector.TopK(embed_top, mat.NewVecDense(len(promptEmbed), promptEmbed), loaded.Embeddings)
  127. for _, e := range topK {
  128. embedding = fmt.Sprintf("%s %s", embedding, e.Embedding.Data)
  129. }
  130. }
  131. prompt, err := model.Prompt(req, embedding)
  132. if err != nil {
  133. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  134. return
  135. }
  136. ch := make(chan any)
  137. go func() {
  138. defer close(ch)
  139. fn := func(r api.GenerateResponse) {
  140. loaded.expireAt = time.Now().Add(sessionDuration)
  141. loaded.expireTimer.Reset(sessionDuration)
  142. r.Model = req.Model
  143. r.CreatedAt = time.Now().UTC()
  144. if r.Done {
  145. r.TotalDuration = time.Since(checkpointStart)
  146. r.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  147. }
  148. ch <- r
  149. }
  150. if err := loaded.llm.Predict(req.Context, prompt, fn); err != nil {
  151. ch <- gin.H{"error": err.Error()}
  152. }
  153. }()
  154. streamResponse(c, ch)
  155. }
  156. func EmbeddingHandler(c *gin.Context) {
  157. loaded.mu.Lock()
  158. defer loaded.mu.Unlock()
  159. var req api.EmbeddingRequest
  160. if err := c.ShouldBindJSON(&req); err != nil {
  161. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  162. return
  163. }
  164. model, err := GetModel(req.Model)
  165. if err != nil {
  166. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  167. return
  168. }
  169. if err := load(model, req.Options, 5*time.Minute); err != nil {
  170. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  171. return
  172. }
  173. if !loaded.options.EmbeddingOnly {
  174. c.JSON(http.StatusBadRequest, gin.H{"error": "embedding option must be set to true"})
  175. return
  176. }
  177. embedding, err := loaded.llm.Embedding(req.Prompt)
  178. if err != nil {
  179. log.Printf("embedding generation failed: %v", err)
  180. c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
  181. return
  182. }
  183. resp := api.EmbeddingResponse{
  184. Embedding: embedding,
  185. }
  186. c.JSON(http.StatusOK, resp)
  187. }
  188. func PullModelHandler(c *gin.Context) {
  189. var req api.PullRequest
  190. if err := c.ShouldBindJSON(&req); err != nil {
  191. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  192. return
  193. }
  194. ch := make(chan any)
  195. go func() {
  196. defer close(ch)
  197. fn := func(r api.ProgressResponse) {
  198. ch <- r
  199. }
  200. regOpts := &RegistryOptions{
  201. Insecure: req.Insecure,
  202. Username: req.Username,
  203. Password: req.Password,
  204. }
  205. ctx, cancel := context.WithCancel(c.Request.Context())
  206. defer cancel()
  207. if err := PullModel(ctx, req.Name, regOpts, fn); err != nil {
  208. ch <- gin.H{"error": err.Error()}
  209. }
  210. }()
  211. streamResponse(c, ch)
  212. }
  213. func PushModelHandler(c *gin.Context) {
  214. var req api.PushRequest
  215. if err := c.ShouldBindJSON(&req); err != nil {
  216. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  217. return
  218. }
  219. ch := make(chan any)
  220. go func() {
  221. defer close(ch)
  222. fn := func(r api.ProgressResponse) {
  223. ch <- r
  224. }
  225. regOpts := &RegistryOptions{
  226. Insecure: req.Insecure,
  227. Username: req.Username,
  228. Password: req.Password,
  229. }
  230. ctx := context.Background()
  231. if err := PushModel(ctx, req.Name, regOpts, fn); err != nil {
  232. ch <- gin.H{"error": err.Error()}
  233. }
  234. }()
  235. streamResponse(c, ch)
  236. }
  237. func CreateModelHandler(c *gin.Context) {
  238. var req api.CreateRequest
  239. if err := c.ShouldBindJSON(&req); err != nil {
  240. c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
  241. return
  242. }
  243. ch := make(chan any)
  244. go func() {
  245. defer close(ch)
  246. fn := func(resp api.ProgressResponse) {
  247. ch <- resp
  248. }
  249. ctx, cancel := context.WithCancel(c.Request.Context())
  250. defer cancel()
  251. if err := CreateModel(ctx, req.Name, req.Path, fn); err != nil {
  252. ch <- gin.H{"error": err.Error()}
  253. }
  254. }()
  255. streamResponse(c, ch)
  256. }
  257. func DeleteModelHandler(c *gin.Context) {
  258. var req api.DeleteRequest
  259. if err := c.ShouldBindJSON(&req); err != nil {
  260. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  261. return
  262. }
  263. if err := DeleteModel(req.Name); err != nil {
  264. if os.IsNotExist(err) {
  265. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  266. } else {
  267. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  268. }
  269. return
  270. }
  271. }
  272. func ListModelsHandler(c *gin.Context) {
  273. var models []api.ListResponseModel
  274. fp, err := GetManifestPath()
  275. if err != nil {
  276. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  277. return
  278. }
  279. err = filepath.Walk(fp, func(path string, info os.FileInfo, err error) error {
  280. if err != nil {
  281. if errors.Is(err, os.ErrNotExist) {
  282. log.Printf("manifest file does not exist: %s", fp)
  283. return nil
  284. }
  285. return err
  286. }
  287. if !info.IsDir() {
  288. fi, err := os.Stat(path)
  289. if err != nil {
  290. log.Printf("skipping file: %s", fp)
  291. return nil
  292. }
  293. path := path[len(fp)+1:]
  294. slashIndex := strings.LastIndex(path, "/")
  295. if slashIndex == -1 {
  296. return nil
  297. }
  298. tag := path[:slashIndex] + ":" + path[slashIndex+1:]
  299. mp, err := ParseModelPath(tag, false)
  300. if err != nil {
  301. return err
  302. }
  303. manifest, err := GetManifest(mp)
  304. if err != nil {
  305. log.Printf("skipping file: %s", fp)
  306. return nil
  307. }
  308. model := api.ListResponseModel{
  309. Name: mp.GetShortTagname(),
  310. Size: manifest.GetTotalSize(),
  311. ModifiedAt: fi.ModTime(),
  312. }
  313. models = append(models, model)
  314. }
  315. return nil
  316. })
  317. if err != nil {
  318. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  319. return
  320. }
  321. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  322. }
  323. func CopyModelHandler(c *gin.Context) {
  324. var req api.CopyRequest
  325. if err := c.ShouldBindJSON(&req); err != nil {
  326. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  327. return
  328. }
  329. if err := CopyModel(req.Source, req.Destination); err != nil {
  330. if os.IsNotExist(err) {
  331. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  332. } else {
  333. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  334. }
  335. return
  336. }
  337. }
  338. func Serve(ln net.Listener, origins []string) error {
  339. config := cors.DefaultConfig()
  340. config.AllowWildcard = true
  341. config.AllowOrigins = append(origins, []string{
  342. "http://localhost",
  343. "http://localhost:*",
  344. "https://localhost",
  345. "https://localhost:*",
  346. "http://127.0.0.1",
  347. "http://127.0.0.1:*",
  348. "https://127.0.0.1",
  349. "https://127.0.0.1:*",
  350. "http://0.0.0.0",
  351. "http://0.0.0.0:*",
  352. "https://0.0.0.0",
  353. "https://0.0.0.0:*",
  354. }...)
  355. r := gin.Default()
  356. r.Use(cors.New(config))
  357. r.GET("/", func(c *gin.Context) {
  358. c.String(http.StatusOK, "Ollama is running")
  359. })
  360. r.HEAD("/", func(c *gin.Context) {
  361. c.Status(http.StatusOK)
  362. })
  363. r.POST("/api/pull", PullModelHandler)
  364. r.POST("/api/generate", GenerateHandler)
  365. r.POST("/api/embeddings", EmbeddingHandler)
  366. r.POST("/api/create", CreateModelHandler)
  367. r.POST("/api/push", PushModelHandler)
  368. r.POST("/api/copy", CopyModelHandler)
  369. r.GET("/api/tags", ListModelsHandler)
  370. r.DELETE("/api/delete", DeleteModelHandler)
  371. log.Printf("Listening on %s", ln.Addr())
  372. s := &http.Server{
  373. Handler: r,
  374. }
  375. return s.Serve(ln)
  376. }
  377. func streamResponse(c *gin.Context, ch chan any) {
  378. c.Header("Content-Type", "application/x-ndjson")
  379. c.Stream(func(w io.Writer) bool {
  380. val, ok := <-ch
  381. if !ok {
  382. return false
  383. }
  384. bts, err := json.Marshal(val)
  385. if err != nil {
  386. log.Printf("streamResponse: json.Marshal failed with %s", err)
  387. return false
  388. }
  389. bts = append(bts, '\n')
  390. if _, err := w.Write(bts); err != nil {
  391. log.Printf("streamResponse: w.Write failed with %s", err)
  392. return false
  393. }
  394. return true
  395. })
  396. }