routes.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. package server
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/fs"
  9. "log"
  10. "net"
  11. "net/http"
  12. "os"
  13. "os/signal"
  14. "path/filepath"
  15. "reflect"
  16. "runtime"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "syscall"
  21. "time"
  22. "github.com/gin-contrib/cors"
  23. "github.com/gin-gonic/gin"
  24. "github.com/jmorganca/ollama/api"
  25. "github.com/jmorganca/ollama/llm"
  26. "github.com/jmorganca/ollama/version"
  27. )
  28. var mode string = gin.DebugMode
  29. func init() {
  30. switch mode {
  31. case gin.DebugMode:
  32. case gin.ReleaseMode:
  33. case gin.TestMode:
  34. default:
  35. mode = gin.DebugMode
  36. }
  37. gin.SetMode(mode)
  38. }
  39. var loaded struct {
  40. mu sync.Mutex
  41. runner llm.LLM
  42. expireAt time.Time
  43. expireTimer *time.Timer
  44. *Model
  45. *api.Options
  46. }
  47. var defaultSessionDuration = 5 * time.Minute
  48. // 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
  49. func load(ctx context.Context, workDir string, model *Model, reqOpts map[string]interface{}, sessionDuration time.Duration) error {
  50. opts := api.DefaultOptions()
  51. if err := opts.FromMap(model.Options); err != nil {
  52. log.Printf("could not load model options: %v", err)
  53. return err
  54. }
  55. if err := opts.FromMap(reqOpts); err != nil {
  56. return err
  57. }
  58. // check if the loaded model is still running in a subprocess, in case something unexpected happened
  59. if loaded.runner != nil {
  60. if err := loaded.runner.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.runner.Close()
  64. loaded.runner = nil
  65. loaded.Model = nil
  66. loaded.Options = nil
  67. }
  68. }
  69. needLoad := loaded.runner == nil || // is there a model loaded?
  70. loaded.ModelPath != model.ModelPath || // has the base model changed?
  71. !reflect.DeepEqual(loaded.AdapterPaths, model.AdapterPaths) || // have the adapters changed?
  72. !reflect.DeepEqual(loaded.Options.Runner, opts.Runner) // have the runner options changed?
  73. if needLoad {
  74. if loaded.runner != nil {
  75. log.Println("changing loaded model")
  76. loaded.runner.Close()
  77. loaded.runner = nil
  78. loaded.Model = nil
  79. loaded.Options = nil
  80. }
  81. llmRunner, err := llm.New(workDir, model.ModelPath, model.AdapterPaths, opts)
  82. if err != nil {
  83. return err
  84. }
  85. loaded.Model = model
  86. loaded.runner = llmRunner
  87. loaded.Options = &opts
  88. }
  89. loaded.expireAt = time.Now().Add(sessionDuration)
  90. if loaded.expireTimer == nil {
  91. loaded.expireTimer = time.AfterFunc(sessionDuration, func() {
  92. loaded.mu.Lock()
  93. defer loaded.mu.Unlock()
  94. if time.Now().Before(loaded.expireAt) {
  95. return
  96. }
  97. if loaded.runner != nil {
  98. loaded.runner.Close()
  99. }
  100. loaded.runner = nil
  101. loaded.Model = nil
  102. loaded.Options = nil
  103. })
  104. }
  105. loaded.expireTimer.Reset(sessionDuration)
  106. return nil
  107. }
  108. func GenerateHandler(c *gin.Context) {
  109. loaded.mu.Lock()
  110. defer loaded.mu.Unlock()
  111. checkpointStart := time.Now()
  112. var req api.GenerateRequest
  113. if err := c.ShouldBindJSON(&req); err != nil {
  114. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  115. return
  116. }
  117. if req.Model == "" {
  118. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  119. return
  120. }
  121. model, err := GetModel(req.Model)
  122. if err != nil {
  123. var pErr *fs.PathError
  124. if errors.As(err, &pErr) {
  125. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  126. return
  127. }
  128. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  129. return
  130. }
  131. workDir := c.GetString("workDir")
  132. // TODO: set this duration from the request if specified
  133. sessionDuration := defaultSessionDuration
  134. if err := load(c.Request.Context(), workDir, model, req.Options, sessionDuration); err != nil {
  135. if errors.Is(err, api.ErrInvalidOpts) {
  136. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  137. return
  138. }
  139. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  140. return
  141. }
  142. checkpointLoaded := time.Now()
  143. prompt, err := model.Prompt(req)
  144. if err != nil {
  145. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  146. return
  147. }
  148. ch := make(chan any)
  149. go func() {
  150. defer close(ch)
  151. // an empty request loads the model
  152. if req.Prompt == "" && req.Template == "" && req.System == "" {
  153. ch <- api.GenerateResponse{CreatedAt: time.Now().UTC(), Model: req.Model, Done: true}
  154. return
  155. }
  156. fn := func(r api.GenerateResponse) {
  157. loaded.expireAt = time.Now().Add(sessionDuration)
  158. loaded.expireTimer.Reset(sessionDuration)
  159. r.Model = req.Model
  160. r.CreatedAt = time.Now().UTC()
  161. if r.Done {
  162. r.TotalDuration = time.Since(checkpointStart)
  163. r.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  164. }
  165. ch <- r
  166. }
  167. if err := loaded.runner.Predict(c.Request.Context(), req.Context, prompt, fn); err != nil {
  168. ch <- gin.H{"error": err.Error()}
  169. }
  170. }()
  171. if req.Stream != nil && !*req.Stream {
  172. var response api.GenerateResponse
  173. generated := ""
  174. for resp := range ch {
  175. if r, ok := resp.(api.GenerateResponse); ok {
  176. generated += r.Response
  177. response = r
  178. } else {
  179. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  180. return
  181. }
  182. }
  183. response.Response = generated
  184. c.JSON(http.StatusOK, response)
  185. return
  186. }
  187. streamResponse(c, ch)
  188. }
  189. func EmbeddingHandler(c *gin.Context) {
  190. loaded.mu.Lock()
  191. defer loaded.mu.Unlock()
  192. var req api.EmbeddingRequest
  193. if err := c.ShouldBindJSON(&req); err != nil {
  194. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  195. return
  196. }
  197. if req.Model == "" {
  198. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  199. return
  200. }
  201. model, err := GetModel(req.Model)
  202. if err != nil {
  203. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  204. return
  205. }
  206. workDir := c.GetString("workDir")
  207. if err := load(c.Request.Context(), workDir, model, req.Options, 5*time.Minute); err != nil {
  208. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  209. return
  210. }
  211. if !loaded.Options.EmbeddingOnly {
  212. c.JSON(http.StatusBadRequest, gin.H{"error": "embedding option must be set to true"})
  213. return
  214. }
  215. embedding, err := loaded.runner.Embedding(c.Request.Context(), req.Prompt)
  216. if err != nil {
  217. log.Printf("embedding generation failed: %v", err)
  218. c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
  219. return
  220. }
  221. resp := api.EmbeddingResponse{
  222. Embedding: embedding,
  223. }
  224. c.JSON(http.StatusOK, resp)
  225. }
  226. func PullModelHandler(c *gin.Context) {
  227. var req api.PullRequest
  228. if err := c.ShouldBindJSON(&req); err != nil {
  229. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  230. return
  231. }
  232. if req.Name == "" {
  233. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  234. return
  235. }
  236. ch := make(chan any)
  237. go func() {
  238. defer close(ch)
  239. fn := func(r api.ProgressResponse) {
  240. ch <- r
  241. }
  242. regOpts := &RegistryOptions{
  243. Insecure: req.Insecure,
  244. }
  245. ctx, cancel := context.WithCancel(c.Request.Context())
  246. defer cancel()
  247. if err := PullModel(ctx, req.Name, regOpts, fn); err != nil {
  248. ch <- gin.H{"error": err.Error()}
  249. }
  250. }()
  251. if req.Stream != nil && !*req.Stream {
  252. waitForStream(c, ch)
  253. return
  254. }
  255. streamResponse(c, ch)
  256. }
  257. func PushModelHandler(c *gin.Context) {
  258. var req api.PushRequest
  259. if err := c.ShouldBindJSON(&req); err != nil {
  260. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  261. return
  262. }
  263. if req.Name == "" {
  264. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  265. return
  266. }
  267. ch := make(chan any)
  268. go func() {
  269. defer close(ch)
  270. fn := func(r api.ProgressResponse) {
  271. ch <- r
  272. }
  273. regOpts := &RegistryOptions{
  274. Insecure: req.Insecure,
  275. }
  276. ctx := context.Background()
  277. if err := PushModel(ctx, req.Name, regOpts, fn); err != nil {
  278. ch <- gin.H{"error": err.Error()}
  279. }
  280. }()
  281. if req.Stream != nil && !*req.Stream {
  282. waitForStream(c, ch)
  283. return
  284. }
  285. streamResponse(c, ch)
  286. }
  287. func CreateModelHandler(c *gin.Context) {
  288. var req api.CreateRequest
  289. if err := c.ShouldBindJSON(&req); err != nil {
  290. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  291. return
  292. }
  293. if req.Name == "" || req.Path == "" {
  294. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name and path are required"})
  295. return
  296. }
  297. ch := make(chan any)
  298. go func() {
  299. defer close(ch)
  300. fn := func(resp api.ProgressResponse) {
  301. ch <- resp
  302. }
  303. ctx, cancel := context.WithCancel(c.Request.Context())
  304. defer cancel()
  305. if err := CreateModel(ctx, req.Name, req.Path, fn); err != nil {
  306. ch <- gin.H{"error": err.Error()}
  307. }
  308. }()
  309. if req.Stream != nil && !*req.Stream {
  310. waitForStream(c, ch)
  311. return
  312. }
  313. streamResponse(c, ch)
  314. }
  315. func DeleteModelHandler(c *gin.Context) {
  316. var req api.DeleteRequest
  317. if err := c.ShouldBindJSON(&req); err != nil {
  318. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  319. return
  320. }
  321. if req.Name == "" {
  322. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  323. return
  324. }
  325. if err := DeleteModel(req.Name); err != nil {
  326. if os.IsNotExist(err) {
  327. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  328. } else {
  329. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  330. }
  331. return
  332. }
  333. manifestsPath, err := GetManifestPath()
  334. if err != nil {
  335. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  336. return
  337. }
  338. if err := PruneDirectory(manifestsPath); err != nil {
  339. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  340. return
  341. }
  342. c.JSON(http.StatusOK, nil)
  343. }
  344. func ShowModelHandler(c *gin.Context) {
  345. var req api.ShowRequest
  346. if err := c.ShouldBindJSON(&req); err != nil {
  347. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  348. return
  349. }
  350. if req.Name == "" {
  351. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  352. return
  353. }
  354. resp, err := GetModelInfo(req.Name)
  355. if err != nil {
  356. if os.IsNotExist(err) {
  357. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  358. } else {
  359. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  360. }
  361. return
  362. }
  363. c.JSON(http.StatusOK, resp)
  364. }
  365. func GetModelInfo(name string) (*api.ShowResponse, error) {
  366. model, err := GetModel(name)
  367. if err != nil {
  368. return nil, err
  369. }
  370. resp := &api.ShowResponse{
  371. License: strings.Join(model.License, "\n"),
  372. System: model.System,
  373. Template: model.Template,
  374. }
  375. mf, err := ShowModelfile(model)
  376. if err != nil {
  377. return nil, err
  378. }
  379. resp.Modelfile = mf
  380. var params []string
  381. cs := 30
  382. for k, v := range model.Options {
  383. switch val := v.(type) {
  384. case string:
  385. params = append(params, fmt.Sprintf("%-*s %s", cs, k, val))
  386. case int:
  387. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(val)))
  388. case float64:
  389. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(val, 'f', 0, 64)))
  390. case bool:
  391. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(val)))
  392. case []interface{}:
  393. for _, nv := range val {
  394. switch nval := nv.(type) {
  395. case string:
  396. params = append(params, fmt.Sprintf("%-*s %s", cs, k, nval))
  397. case int:
  398. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(nval)))
  399. case float64:
  400. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(nval, 'f', 0, 64)))
  401. case bool:
  402. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(nval)))
  403. }
  404. }
  405. }
  406. }
  407. resp.Parameters = strings.Join(params, "\n")
  408. return resp, nil
  409. }
  410. func ListModelsHandler(c *gin.Context) {
  411. models := make([]api.ModelResponse, 0)
  412. fp, err := GetManifestPath()
  413. if err != nil {
  414. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  415. return
  416. }
  417. walkFunc := func(path string, info os.FileInfo, _ error) error {
  418. if !info.IsDir() {
  419. dir, file := filepath.Split(path)
  420. dir = strings.Trim(strings.TrimPrefix(dir, fp), string(os.PathSeparator))
  421. tag := strings.Join([]string{dir, file}, ":")
  422. mp := ParseModelPath(tag)
  423. manifest, digest, err := GetManifest(mp)
  424. if err != nil {
  425. log.Printf("skipping file: %s", fp)
  426. return nil
  427. }
  428. models = append(models, api.ModelResponse{
  429. Name: mp.GetShortTagname(),
  430. Size: manifest.GetTotalSize(),
  431. Digest: digest,
  432. ModifiedAt: info.ModTime(),
  433. })
  434. }
  435. return nil
  436. }
  437. if err := filepath.Walk(fp, walkFunc); err != nil {
  438. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  439. return
  440. }
  441. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  442. }
  443. func CopyModelHandler(c *gin.Context) {
  444. var req api.CopyRequest
  445. if err := c.ShouldBindJSON(&req); err != nil {
  446. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  447. return
  448. }
  449. if req.Source == "" || req.Destination == "" {
  450. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
  451. return
  452. }
  453. if err := CopyModel(req.Source, req.Destination); err != nil {
  454. if os.IsNotExist(err) {
  455. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  456. } else {
  457. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  458. }
  459. return
  460. }
  461. }
  462. var defaultAllowOrigins = []string{
  463. "localhost",
  464. "127.0.0.1",
  465. "0.0.0.0",
  466. }
  467. func Serve(ln net.Listener, allowOrigins []string) error {
  468. config := cors.DefaultConfig()
  469. config.AllowWildcard = true
  470. config.AllowOrigins = allowOrigins
  471. for _, allowOrigin := range defaultAllowOrigins {
  472. config.AllowOrigins = append(config.AllowOrigins,
  473. fmt.Sprintf("http://%s", allowOrigin),
  474. fmt.Sprintf("https://%s", allowOrigin),
  475. fmt.Sprintf("http://%s:*", allowOrigin),
  476. fmt.Sprintf("https://%s:*", allowOrigin),
  477. )
  478. }
  479. workDir, err := os.MkdirTemp("", "ollama")
  480. if err != nil {
  481. return err
  482. }
  483. defer os.RemoveAll(workDir)
  484. r := gin.Default()
  485. r.Use(
  486. cors.New(config),
  487. func(c *gin.Context) {
  488. c.Set("workDir", workDir)
  489. c.Next()
  490. },
  491. )
  492. r.POST("/api/pull", PullModelHandler)
  493. r.POST("/api/generate", GenerateHandler)
  494. r.POST("/api/embeddings", EmbeddingHandler)
  495. r.POST("/api/create", CreateModelHandler)
  496. r.POST("/api/push", PushModelHandler)
  497. r.POST("/api/copy", CopyModelHandler)
  498. r.DELETE("/api/delete", DeleteModelHandler)
  499. r.POST("/api/show", ShowModelHandler)
  500. for _, method := range []string{http.MethodGet, http.MethodHead} {
  501. r.Handle(method, "/", func(c *gin.Context) {
  502. c.String(http.StatusOK, "Ollama is running")
  503. })
  504. r.Handle(method, "/api/tags", ListModelsHandler)
  505. }
  506. log.Printf("Listening on %s (version %s)", ln.Addr(), version.Version)
  507. s := &http.Server{
  508. Handler: r,
  509. }
  510. // listen for a ctrl+c and stop any loaded llm
  511. signals := make(chan os.Signal, 1)
  512. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  513. go func() {
  514. <-signals
  515. if loaded.runner != nil {
  516. loaded.runner.Close()
  517. }
  518. os.RemoveAll(workDir)
  519. os.Exit(0)
  520. }()
  521. if runtime.GOOS == "linux" {
  522. // check compatibility to log warnings
  523. if _, err := llm.CheckVRAM(); err != nil {
  524. log.Printf("Warning: GPU support may not enabled, check you have installed install GPU drivers: %v", err)
  525. }
  526. }
  527. return s.Serve(ln)
  528. }
  529. func waitForStream(c *gin.Context, ch chan interface{}) {
  530. c.Header("Content-Type", "application/json")
  531. for resp := range ch {
  532. switch r := resp.(type) {
  533. case api.ProgressResponse:
  534. if r.Status == "success" {
  535. c.JSON(http.StatusOK, r)
  536. return
  537. }
  538. case gin.H:
  539. if errorMsg, ok := r["error"].(string); ok {
  540. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  541. return
  542. } else {
  543. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  544. return
  545. }
  546. default:
  547. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  548. return
  549. }
  550. }
  551. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  552. }
  553. func streamResponse(c *gin.Context, ch chan any) {
  554. c.Header("Content-Type", "application/x-ndjson")
  555. c.Stream(func(w io.Writer) bool {
  556. val, ok := <-ch
  557. if !ok {
  558. return false
  559. }
  560. bts, err := json.Marshal(val)
  561. if err != nil {
  562. log.Printf("streamResponse: json.Marshal failed with %s", err)
  563. return false
  564. }
  565. // Delineate chunks with new-line delimiter
  566. bts = append(bts, '\n')
  567. if _, err := w.Write(bts); err != nil {
  568. log.Printf("streamResponse: w.Write failed with %s", err)
  569. return false
  570. }
  571. return true
  572. })
  573. }