routes.go 12 KB

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