routes.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. ctx := context.Background()
  230. if err := PushModel(ctx, req.Name, regOpts, fn); err != nil {
  231. ch <- gin.H{"error": err.Error()}
  232. }
  233. }()
  234. streamResponse(c, ch)
  235. }
  236. func CreateModelHandler(c *gin.Context) {
  237. var req api.CreateRequest
  238. if err := c.ShouldBindJSON(&req); err != nil {
  239. c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
  240. return
  241. }
  242. ch := make(chan any)
  243. go func() {
  244. defer close(ch)
  245. fn := func(resp api.ProgressResponse) {
  246. ch <- resp
  247. }
  248. ctx, cancel := context.WithCancel(c.Request.Context())
  249. defer cancel()
  250. if err := CreateModel(ctx, req.Name, req.Path, fn); err != nil {
  251. ch <- gin.H{"error": err.Error()}
  252. }
  253. }()
  254. streamResponse(c, ch)
  255. }
  256. func DeleteModelHandler(c *gin.Context) {
  257. var req api.DeleteRequest
  258. if err := c.ShouldBindJSON(&req); err != nil {
  259. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  260. return
  261. }
  262. if err := DeleteModel(req.Name); err != nil {
  263. if os.IsNotExist(err) {
  264. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  265. } else {
  266. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  267. }
  268. return
  269. }
  270. }
  271. func ListModelsHandler(c *gin.Context) {
  272. var models []api.ListResponseModel
  273. fp, err := GetManifestPath()
  274. if err != nil {
  275. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  276. return
  277. }
  278. err = filepath.Walk(fp, func(path string, info os.FileInfo, err error) error {
  279. if err != nil {
  280. if errors.Is(err, os.ErrNotExist) {
  281. log.Printf("manifest file does not exist: %s", fp)
  282. return nil
  283. }
  284. return err
  285. }
  286. if !info.IsDir() {
  287. fi, err := os.Stat(path)
  288. if err != nil {
  289. log.Printf("skipping file: %s", fp)
  290. return nil
  291. }
  292. path := path[len(fp)+1:]
  293. slashIndex := strings.LastIndex(path, "/")
  294. if slashIndex == -1 {
  295. return nil
  296. }
  297. tag := path[:slashIndex] + ":" + path[slashIndex+1:]
  298. mp := ParseModelPath(tag)
  299. manifest, err := GetManifest(mp)
  300. if err != nil {
  301. log.Printf("skipping file: %s", fp)
  302. return nil
  303. }
  304. model := api.ListResponseModel{
  305. Name: mp.GetShortTagname(),
  306. Size: manifest.GetTotalSize(),
  307. ModifiedAt: fi.ModTime(),
  308. }
  309. models = append(models, model)
  310. }
  311. return nil
  312. })
  313. if err != nil {
  314. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  315. return
  316. }
  317. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  318. }
  319. func CopyModelHandler(c *gin.Context) {
  320. var req api.CopyRequest
  321. if err := c.ShouldBindJSON(&req); err != nil {
  322. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  323. return
  324. }
  325. if err := CopyModel(req.Source, req.Destination); err != nil {
  326. if os.IsNotExist(err) {
  327. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  328. } else {
  329. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  330. }
  331. return
  332. }
  333. }
  334. func Serve(ln net.Listener, origins []string) error {
  335. config := cors.DefaultConfig()
  336. config.AllowWildcard = true
  337. config.AllowOrigins = append(origins, []string{
  338. "http://localhost",
  339. "http://localhost:*",
  340. "https://localhost",
  341. "https://localhost:*",
  342. "http://127.0.0.1",
  343. "http://127.0.0.1:*",
  344. "https://127.0.0.1",
  345. "https://127.0.0.1:*",
  346. "http://0.0.0.0",
  347. "http://0.0.0.0:*",
  348. "https://0.0.0.0",
  349. "https://0.0.0.0:*",
  350. }...)
  351. r := gin.Default()
  352. r.Use(cors.New(config))
  353. r.GET("/", func(c *gin.Context) {
  354. c.String(http.StatusOK, "Ollama is running")
  355. })
  356. r.HEAD("/", func(c *gin.Context) {
  357. c.Status(http.StatusOK)
  358. })
  359. r.POST("/api/pull", PullModelHandler)
  360. r.POST("/api/generate", GenerateHandler)
  361. r.POST("/api/embeddings", EmbeddingHandler)
  362. r.POST("/api/create", CreateModelHandler)
  363. r.POST("/api/push", PushModelHandler)
  364. r.POST("/api/copy", CopyModelHandler)
  365. r.GET("/api/tags", ListModelsHandler)
  366. r.DELETE("/api/delete", DeleteModelHandler)
  367. log.Printf("Listening on %s", ln.Addr())
  368. s := &http.Server{
  369. Handler: r,
  370. }
  371. return s.Serve(ln)
  372. }
  373. func streamResponse(c *gin.Context, ch chan any) {
  374. c.Header("Content-Type", "application/x-ndjson")
  375. c.Stream(func(w io.Writer) bool {
  376. val, ok := <-ch
  377. if !ok {
  378. return false
  379. }
  380. bts, err := json.Marshal(val)
  381. if err != nil {
  382. log.Printf("streamResponse: json.Marshal failed with %s", err)
  383. return false
  384. }
  385. bts = append(bts, '\n')
  386. if _, err := w.Write(bts); err != nil {
  387. log.Printf("streamResponse: w.Write failed with %s", err)
  388. return false
  389. }
  390. return true
  391. })
  392. }