routes.go 10 KB

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