routes.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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. model, err := GetModel(req.Model)
  118. if err != nil {
  119. var pErr *fs.PathError
  120. if errors.As(err, &pErr) {
  121. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  122. return
  123. }
  124. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  125. return
  126. }
  127. workDir := c.GetString("workDir")
  128. // TODO: set this duration from the request if specified
  129. sessionDuration := defaultSessionDuration
  130. if err := load(c.Request.Context(), workDir, model, req.Options, sessionDuration); err != nil {
  131. if errors.Is(err, api.ErrInvalidOpts) {
  132. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  133. return
  134. }
  135. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  136. return
  137. }
  138. checkpointLoaded := time.Now()
  139. prompt, err := model.Prompt(req)
  140. if err != nil {
  141. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  142. return
  143. }
  144. ch := make(chan any)
  145. go func() {
  146. defer close(ch)
  147. fn := func(r api.GenerateResponse) {
  148. loaded.expireAt = time.Now().Add(sessionDuration)
  149. loaded.expireTimer.Reset(sessionDuration)
  150. r.Model = req.Model
  151. r.CreatedAt = time.Now().UTC()
  152. if r.Done {
  153. r.TotalDuration = time.Since(checkpointStart)
  154. r.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  155. }
  156. ch <- r
  157. }
  158. // an empty request loads the model
  159. if req.Prompt == "" && req.Template == "" && req.System == "" {
  160. ch <- api.GenerateResponse{Model: req.Model, Done: true}
  161. } else {
  162. if err := loaded.runner.Predict(c.Request.Context(), req.Context, prompt, fn); err != nil {
  163. ch <- gin.H{"error": err.Error()}
  164. }
  165. }
  166. }()
  167. if req.Stream != nil && !*req.Stream {
  168. var response api.GenerateResponse
  169. generated := ""
  170. for resp := range ch {
  171. if r, ok := resp.(api.GenerateResponse); ok {
  172. generated += r.Response
  173. response = r
  174. } else {
  175. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  176. return
  177. }
  178. }
  179. response.Response = generated
  180. c.JSON(http.StatusOK, response)
  181. return
  182. }
  183. streamResponse(c, ch)
  184. }
  185. func EmbeddingHandler(c *gin.Context) {
  186. loaded.mu.Lock()
  187. defer loaded.mu.Unlock()
  188. var req api.EmbeddingRequest
  189. if err := c.ShouldBindJSON(&req); err != nil {
  190. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  191. return
  192. }
  193. model, err := GetModel(req.Model)
  194. if err != nil {
  195. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  196. return
  197. }
  198. workDir := c.GetString("workDir")
  199. if err := load(c.Request.Context(), workDir, 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.runner.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. }
  233. ctx, cancel := context.WithCancel(c.Request.Context())
  234. defer cancel()
  235. if err := PullModel(ctx, req.Name, regOpts, fn); err != nil {
  236. ch <- gin.H{"error": err.Error()}
  237. }
  238. }()
  239. if req.Stream != nil && !*req.Stream {
  240. waitForStream(c, ch)
  241. return
  242. }
  243. streamResponse(c, ch)
  244. }
  245. func PushModelHandler(c *gin.Context) {
  246. var req api.PushRequest
  247. if err := c.ShouldBindJSON(&req); err != nil {
  248. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  249. return
  250. }
  251. ch := make(chan any)
  252. go func() {
  253. defer close(ch)
  254. fn := func(r api.ProgressResponse) {
  255. ch <- r
  256. }
  257. regOpts := &RegistryOptions{
  258. Insecure: req.Insecure,
  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. if req.Stream != nil && !*req.Stream {
  266. waitForStream(c, ch)
  267. return
  268. }
  269. streamResponse(c, ch)
  270. }
  271. func CreateModelHandler(c *gin.Context) {
  272. var req api.CreateRequest
  273. if err := c.ShouldBindJSON(&req); err != nil {
  274. c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
  275. return
  276. }
  277. workDir := c.GetString("workDir")
  278. ch := make(chan any)
  279. go func() {
  280. defer close(ch)
  281. fn := func(resp api.ProgressResponse) {
  282. ch <- resp
  283. }
  284. ctx, cancel := context.WithCancel(c.Request.Context())
  285. defer cancel()
  286. if err := CreateModel(ctx, workDir, req.Name, req.Path, fn); err != nil {
  287. ch <- gin.H{"error": err.Error()}
  288. }
  289. }()
  290. if req.Stream != nil && !*req.Stream {
  291. waitForStream(c, ch)
  292. return
  293. }
  294. streamResponse(c, ch)
  295. }
  296. func DeleteModelHandler(c *gin.Context) {
  297. var req api.DeleteRequest
  298. if err := c.ShouldBindJSON(&req); err != nil {
  299. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  300. return
  301. }
  302. if err := DeleteModel(req.Name); err != nil {
  303. if os.IsNotExist(err) {
  304. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  305. } else {
  306. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  307. }
  308. return
  309. }
  310. manifestsPath, err := GetManifestPath()
  311. if err != nil {
  312. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  313. return
  314. }
  315. if err := PruneDirectory(manifestsPath); err != nil {
  316. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  317. return
  318. }
  319. c.JSON(http.StatusOK, nil)
  320. }
  321. func ShowModelHandler(c *gin.Context) {
  322. var req api.ShowRequest
  323. if err := c.ShouldBindJSON(&req); err != nil {
  324. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  325. return
  326. }
  327. resp, err := GetModelInfo(req.Name)
  328. if err != nil {
  329. if os.IsNotExist(err) {
  330. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  331. } else {
  332. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  333. }
  334. return
  335. }
  336. c.JSON(http.StatusOK, resp)
  337. }
  338. func GetModelInfo(name string) (*api.ShowResponse, error) {
  339. model, err := GetModel(name)
  340. if err != nil {
  341. return nil, err
  342. }
  343. resp := &api.ShowResponse{
  344. License: strings.Join(model.License, "\n"),
  345. System: model.System,
  346. Template: model.Template,
  347. }
  348. mf, err := ShowModelfile(model)
  349. if err != nil {
  350. return nil, err
  351. }
  352. resp.Modelfile = mf
  353. var params []string
  354. cs := 30
  355. for k, v := range model.Options {
  356. switch val := v.(type) {
  357. case string:
  358. params = append(params, fmt.Sprintf("%-*s %s", cs, k, val))
  359. case int:
  360. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(val)))
  361. case float64:
  362. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(val, 'f', 0, 64)))
  363. case bool:
  364. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(val)))
  365. case []interface{}:
  366. for _, nv := range val {
  367. switch nval := nv.(type) {
  368. case string:
  369. params = append(params, fmt.Sprintf("%-*s %s", cs, k, nval))
  370. case int:
  371. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(nval)))
  372. case float64:
  373. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(nval, 'f', 0, 64)))
  374. case bool:
  375. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(nval)))
  376. }
  377. }
  378. }
  379. }
  380. resp.Parameters = strings.Join(params, "\n")
  381. return resp, nil
  382. }
  383. func ListModelsHandler(c *gin.Context) {
  384. models := make([]api.ModelResponse, 0)
  385. fp, err := GetManifestPath()
  386. if err != nil {
  387. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  388. return
  389. }
  390. walkFunc := func(path string, info os.FileInfo, _ error) error {
  391. if !info.IsDir() {
  392. dir, file := filepath.Split(path)
  393. dir = strings.Trim(strings.TrimPrefix(dir, fp), string(os.PathSeparator))
  394. tag := strings.Join([]string{dir, file}, ":")
  395. mp := ParseModelPath(tag)
  396. manifest, digest, err := GetManifest(mp)
  397. if err != nil {
  398. log.Printf("skipping file: %s", fp)
  399. return nil
  400. }
  401. models = append(models, api.ModelResponse{
  402. Name: mp.GetShortTagname(),
  403. Size: manifest.GetTotalSize(),
  404. Digest: digest,
  405. ModifiedAt: info.ModTime(),
  406. })
  407. }
  408. return nil
  409. }
  410. if err := filepath.Walk(fp, walkFunc); err != nil {
  411. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  412. return
  413. }
  414. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  415. }
  416. func CopyModelHandler(c *gin.Context) {
  417. var req api.CopyRequest
  418. if err := c.ShouldBindJSON(&req); err != nil {
  419. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  420. return
  421. }
  422. if err := CopyModel(req.Source, req.Destination); err != nil {
  423. if os.IsNotExist(err) {
  424. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  425. } else {
  426. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  427. }
  428. return
  429. }
  430. }
  431. var defaultAllowOrigins = []string{
  432. "localhost",
  433. "127.0.0.1",
  434. "0.0.0.0",
  435. }
  436. func Serve(ln net.Listener, allowOrigins []string) error {
  437. config := cors.DefaultConfig()
  438. config.AllowWildcard = true
  439. config.AllowOrigins = allowOrigins
  440. for _, allowOrigin := range defaultAllowOrigins {
  441. config.AllowOrigins = append(config.AllowOrigins,
  442. fmt.Sprintf("http://%s", allowOrigin),
  443. fmt.Sprintf("https://%s", allowOrigin),
  444. fmt.Sprintf("http://%s:*", allowOrigin),
  445. fmt.Sprintf("https://%s:*", allowOrigin),
  446. )
  447. }
  448. workDir, err := os.MkdirTemp("", "ollama")
  449. if err != nil {
  450. return err
  451. }
  452. defer os.RemoveAll(workDir)
  453. r := gin.Default()
  454. r.Use(
  455. cors.New(config),
  456. func(c *gin.Context) {
  457. c.Set("workDir", workDir)
  458. c.Next()
  459. },
  460. )
  461. r.POST("/api/pull", PullModelHandler)
  462. r.POST("/api/generate", GenerateHandler)
  463. r.POST("/api/embeddings", EmbeddingHandler)
  464. r.POST("/api/create", CreateModelHandler)
  465. r.POST("/api/push", PushModelHandler)
  466. r.POST("/api/copy", CopyModelHandler)
  467. r.DELETE("/api/delete", DeleteModelHandler)
  468. r.POST("/api/show", ShowModelHandler)
  469. for _, method := range []string{http.MethodGet, http.MethodHead} {
  470. r.Handle(method, "/", func(c *gin.Context) {
  471. c.String(http.StatusOK, "Ollama is running")
  472. })
  473. r.Handle(method, "/api/tags", ListModelsHandler)
  474. }
  475. log.Printf("Listening on %s (version %s)", ln.Addr(), version.Version)
  476. s := &http.Server{
  477. Handler: r,
  478. }
  479. // listen for a ctrl+c and stop any loaded llm
  480. signals := make(chan os.Signal, 1)
  481. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  482. go func() {
  483. <-signals
  484. if loaded.runner != nil {
  485. loaded.runner.Close()
  486. }
  487. os.RemoveAll(workDir)
  488. os.Exit(0)
  489. }()
  490. if runtime.GOOS == "linux" {
  491. // check compatibility to log warnings
  492. if _, err := llm.CheckVRAM(); err != nil {
  493. log.Printf("Warning: GPU support may not enabled, check you have installed install GPU drivers: %v", err)
  494. }
  495. }
  496. return s.Serve(ln)
  497. }
  498. func waitForStream(c *gin.Context, ch chan interface{}) {
  499. c.Header("Content-Type", "application/json")
  500. for resp := range ch {
  501. switch r := resp.(type) {
  502. case api.ProgressResponse:
  503. if r.Status == "success" {
  504. c.JSON(http.StatusOK, r)
  505. return
  506. }
  507. case gin.H:
  508. if errorMsg, ok := r["error"].(string); ok {
  509. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  510. return
  511. } else {
  512. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  513. return
  514. }
  515. default:
  516. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  517. return
  518. }
  519. }
  520. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  521. }
  522. func streamResponse(c *gin.Context, ch chan any) {
  523. c.Header("Content-Type", "application/x-ndjson")
  524. c.Stream(func(w io.Writer) bool {
  525. val, ok := <-ch
  526. if !ok {
  527. return false
  528. }
  529. bts, err := json.Marshal(val)
  530. if err != nil {
  531. log.Printf("streamResponse: json.Marshal failed with %s", err)
  532. return false
  533. }
  534. // Delineate chunks with new-line delimiter
  535. bts = append(bts, '\n')
  536. if _, err := w.Write(bts); err != nil {
  537. log.Printf("streamResponse: w.Write failed with %s", err)
  538. return false
  539. }
  540. return true
  541. })
  542. }