routes.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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/llama"
  22. "github.com/jmorganca/ollama/vector"
  23. )
  24. var loaded struct {
  25. mu sync.Mutex
  26. llm *llama.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. llm, err := llama.New(model.ModelPath, opts)
  55. if err != nil {
  56. return err
  57. }
  58. if opts.NumKeep < 0 {
  59. promptWithSystem, err := model.Prompt(api.GenerateRequest{}, "")
  60. if err != nil {
  61. return err
  62. }
  63. promptNoSystem, err := model.Prompt(api.GenerateRequest{Context: []int{0}}, "")
  64. if err != nil {
  65. return err
  66. }
  67. tokensWithSystem := llm.Encode(promptWithSystem)
  68. tokensNoSystem := llm.Encode(promptNoSystem)
  69. llm.NumKeep = len(tokensWithSystem) - len(tokensNoSystem) + 1
  70. }
  71. loaded.llm = llm
  72. loaded.digest = model.Digest
  73. loaded.options = opts
  74. }
  75. loaded.expireAt = time.Now().Add(sessionDuration)
  76. if loaded.expireTimer == nil {
  77. loaded.expireTimer = time.AfterFunc(sessionDuration, func() {
  78. loaded.mu.Lock()
  79. defer loaded.mu.Unlock()
  80. if time.Now().Before(loaded.expireAt) {
  81. return
  82. }
  83. if loaded.llm == nil {
  84. return
  85. }
  86. loaded.llm.Close()
  87. loaded.llm = nil
  88. loaded.digest = ""
  89. })
  90. }
  91. loaded.expireTimer.Reset(sessionDuration)
  92. return nil
  93. }
  94. func GenerateHandler(c *gin.Context) {
  95. loaded.mu.Lock()
  96. defer loaded.mu.Unlock()
  97. checkpointStart := time.Now()
  98. var req api.GenerateRequest
  99. if err := c.ShouldBindJSON(&req); err != nil {
  100. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  101. return
  102. }
  103. model, err := GetModel(req.Model)
  104. if err != nil {
  105. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  106. return
  107. }
  108. sessionDuration := 5 * time.Minute
  109. if err := load(model, req.Options, sessionDuration); err != nil {
  110. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  111. return
  112. }
  113. checkpointLoaded := time.Now()
  114. embedding := ""
  115. if model.Embeddings != nil && len(model.Embeddings) > 0 {
  116. promptEmbed, err := loaded.llm.Embedding(req.Prompt)
  117. if err != nil {
  118. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  119. return
  120. }
  121. // TODO: set embed_top from specified parameters in modelfile
  122. embed_top := 3
  123. topK := vector.TopK(embed_top, mat.NewVecDense(len(promptEmbed), promptEmbed), loaded.Embeddings)
  124. for _, e := range topK {
  125. embedding = fmt.Sprintf("%s %s", embedding, e.Embedding.Data)
  126. }
  127. }
  128. prompt, err := model.Prompt(req, embedding)
  129. if err != nil {
  130. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  131. return
  132. }
  133. ch := make(chan any)
  134. go func() {
  135. defer close(ch)
  136. fn := func(r api.GenerateResponse) {
  137. loaded.expireAt = time.Now().Add(sessionDuration)
  138. loaded.expireTimer.Reset(sessionDuration)
  139. r.Model = req.Model
  140. r.CreatedAt = time.Now().UTC()
  141. if r.Done {
  142. r.TotalDuration = time.Since(checkpointStart)
  143. r.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  144. }
  145. ch <- r
  146. }
  147. if err := loaded.llm.Predict(req.Context, prompt, fn); err != nil {
  148. ch <- gin.H{"error": err.Error()}
  149. }
  150. }()
  151. streamResponse(c, ch)
  152. }
  153. func EmbeddingHandler(c *gin.Context) {
  154. loaded.mu.Lock()
  155. defer loaded.mu.Unlock()
  156. var req api.EmbeddingRequest
  157. if err := c.ShouldBindJSON(&req); err != nil {
  158. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  159. return
  160. }
  161. model, err := GetModel(req.Model)
  162. if err != nil {
  163. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  164. return
  165. }
  166. if err := load(model, req.Options, 5*time.Minute); err != nil {
  167. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  168. return
  169. }
  170. if !loaded.options.EmbeddingOnly {
  171. c.JSON(http.StatusBadRequest, gin.H{"error": "embedding option must be set to true"})
  172. return
  173. }
  174. embedding, err := loaded.llm.Embedding(req.Prompt)
  175. if err != nil {
  176. log.Printf("embedding generation failed: %v", err)
  177. c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
  178. return
  179. }
  180. resp := api.EmbeddingResponse{
  181. Embedding: embedding,
  182. }
  183. c.JSON(http.StatusOK, resp)
  184. }
  185. func PullModelHandler(c *gin.Context) {
  186. var req api.PullRequest
  187. if err := c.ShouldBindJSON(&req); err != nil {
  188. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  189. return
  190. }
  191. ch := make(chan any)
  192. go func() {
  193. defer close(ch)
  194. fn := func(r api.ProgressResponse) {
  195. ch <- r
  196. }
  197. regOpts := &RegistryOptions{
  198. Insecure: req.Insecure,
  199. Username: req.Username,
  200. Password: req.Password,
  201. }
  202. ctx, cancel := context.WithCancel(c.Request.Context())
  203. defer cancel()
  204. if err := PullModel(ctx, req.Name, regOpts, fn); err != nil {
  205. ch <- gin.H{"error": err.Error()}
  206. }
  207. }()
  208. streamResponse(c, ch)
  209. }
  210. func PushModelHandler(c *gin.Context) {
  211. var req api.PushRequest
  212. if err := c.ShouldBindJSON(&req); err != nil {
  213. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  214. return
  215. }
  216. ch := make(chan any)
  217. go func() {
  218. defer close(ch)
  219. fn := func(r api.ProgressResponse) {
  220. ch <- r
  221. }
  222. regOpts := &RegistryOptions{
  223. Insecure: req.Insecure,
  224. Username: req.Username,
  225. Password: req.Password,
  226. }
  227. if err := PushModel(req.Name, regOpts, fn); err != nil {
  228. ch <- gin.H{"error": err.Error()}
  229. }
  230. }()
  231. streamResponse(c, ch)
  232. }
  233. func CreateModelHandler(c *gin.Context) {
  234. var req api.CreateRequest
  235. if err := c.ShouldBindJSON(&req); err != nil {
  236. c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
  237. return
  238. }
  239. ch := make(chan any)
  240. go func() {
  241. defer close(ch)
  242. fn := func(resp api.ProgressResponse) {
  243. ch <- resp
  244. }
  245. ctx, cancel := context.WithCancel(c.Request.Context())
  246. defer cancel()
  247. if err := CreateModel(ctx, req.Name, req.Path, fn); err != nil {
  248. ch <- gin.H{"error": err.Error()}
  249. }
  250. }()
  251. streamResponse(c, ch)
  252. }
  253. func DeleteModelHandler(c *gin.Context) {
  254. var req api.DeleteRequest
  255. if err := c.ShouldBindJSON(&req); err != nil {
  256. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  257. return
  258. }
  259. if err := DeleteModel(req.Name); err != nil {
  260. if os.IsNotExist(err) {
  261. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  262. } else {
  263. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  264. }
  265. return
  266. }
  267. }
  268. func ListModelsHandler(c *gin.Context) {
  269. var models []api.ListResponseModel
  270. fp, err := GetManifestPath()
  271. if err != nil {
  272. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  273. return
  274. }
  275. err = filepath.Walk(fp, func(path string, info os.FileInfo, err error) error {
  276. if err != nil {
  277. if errors.Is(err, os.ErrNotExist) {
  278. log.Printf("manifest file does not exist: %s", fp)
  279. return nil
  280. }
  281. return err
  282. }
  283. if !info.IsDir() {
  284. fi, err := os.Stat(path)
  285. if err != nil {
  286. log.Printf("skipping file: %s", fp)
  287. return nil
  288. }
  289. path := path[len(fp)+1:]
  290. slashIndex := strings.LastIndex(path, "/")
  291. if slashIndex == -1 {
  292. return nil
  293. }
  294. tag := path[:slashIndex] + ":" + path[slashIndex+1:]
  295. mp := ParseModelPath(tag)
  296. manifest, err := GetManifest(mp)
  297. if err != nil {
  298. log.Printf("skipping file: %s", fp)
  299. return nil
  300. }
  301. model := api.ListResponseModel{
  302. Name: mp.GetShortTagname(),
  303. Size: manifest.GetTotalSize(),
  304. ModifiedAt: fi.ModTime(),
  305. }
  306. models = append(models, model)
  307. }
  308. return nil
  309. })
  310. if err != nil {
  311. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  312. return
  313. }
  314. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  315. }
  316. func CopyModelHandler(c *gin.Context) {
  317. var req api.CopyRequest
  318. if err := c.ShouldBindJSON(&req); err != nil {
  319. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  320. return
  321. }
  322. if err := CopyModel(req.Source, req.Destination); err != nil {
  323. if os.IsNotExist(err) {
  324. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  325. } else {
  326. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  327. }
  328. return
  329. }
  330. }
  331. func Serve(ln net.Listener, extraOrigins []string) error {
  332. config := cors.DefaultConfig()
  333. config.AllowWildcard = true
  334. allowedOrigins := []string{
  335. "http://localhost",
  336. "http://localhost:*",
  337. "https://localhost",
  338. "https://localhost:*",
  339. "http://127.0.0.1",
  340. "http://127.0.0.1:*",
  341. "https://127.0.0.1",
  342. "https://127.0.0.1:*",
  343. "http://0.0.0.0",
  344. "http://0.0.0.0:*",
  345. "https://0.0.0.0",
  346. "https://0.0.0.0:*",
  347. }
  348. allowedOrigins = append(allowedOrigins, extraOrigins...)
  349. config.AllowOrigins = allowedOrigins
  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. }