routes.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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. ch := make(chan any)
  278. go func() {
  279. defer close(ch)
  280. fn := func(resp api.ProgressResponse) {
  281. ch <- resp
  282. }
  283. ctx, cancel := context.WithCancel(c.Request.Context())
  284. defer cancel()
  285. if err := CreateModel(ctx, req.Name, req.Path, fn); err != nil {
  286. ch <- gin.H{"error": err.Error()}
  287. }
  288. }()
  289. if req.Stream != nil && !*req.Stream {
  290. waitForStream(c, ch)
  291. return
  292. }
  293. streamResponse(c, ch)
  294. }
  295. func DeleteModelHandler(c *gin.Context) {
  296. var req api.DeleteRequest
  297. if err := c.ShouldBindJSON(&req); err != nil {
  298. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  299. return
  300. }
  301. if err := DeleteModel(req.Name); err != nil {
  302. if os.IsNotExist(err) {
  303. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  304. } else {
  305. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  306. }
  307. return
  308. }
  309. manifestsPath, err := GetManifestPath()
  310. if err != nil {
  311. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  312. return
  313. }
  314. if err := PruneDirectory(manifestsPath); err != nil {
  315. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  316. return
  317. }
  318. c.JSON(http.StatusOK, nil)
  319. }
  320. func ShowModelHandler(c *gin.Context) {
  321. var req api.ShowRequest
  322. if err := c.ShouldBindJSON(&req); err != nil {
  323. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  324. return
  325. }
  326. resp, err := GetModelInfo(req.Name)
  327. if err != nil {
  328. if os.IsNotExist(err) {
  329. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  330. } else {
  331. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  332. }
  333. return
  334. }
  335. c.JSON(http.StatusOK, resp)
  336. }
  337. func GetModelInfo(name string) (*api.ShowResponse, error) {
  338. model, err := GetModel(name)
  339. if err != nil {
  340. return nil, err
  341. }
  342. resp := &api.ShowResponse{
  343. License: strings.Join(model.License, "\n"),
  344. System: model.System,
  345. Template: model.Template,
  346. }
  347. mf, err := ShowModelfile(model)
  348. if err != nil {
  349. return nil, err
  350. }
  351. resp.Modelfile = mf
  352. var params []string
  353. cs := 30
  354. for k, v := range model.Options {
  355. switch val := v.(type) {
  356. case string:
  357. params = append(params, fmt.Sprintf("%-*s %s", cs, k, val))
  358. case int:
  359. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(val)))
  360. case float64:
  361. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(val, 'f', 0, 64)))
  362. case bool:
  363. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(val)))
  364. case []interface{}:
  365. for _, nv := range val {
  366. switch nval := nv.(type) {
  367. case string:
  368. params = append(params, fmt.Sprintf("%-*s %s", cs, k, nval))
  369. case int:
  370. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(nval)))
  371. case float64:
  372. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(nval, 'f', 0, 64)))
  373. case bool:
  374. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(nval)))
  375. }
  376. }
  377. }
  378. }
  379. resp.Parameters = strings.Join(params, "\n")
  380. return resp, nil
  381. }
  382. func ListModelsHandler(c *gin.Context) {
  383. models := make([]api.ModelResponse, 0)
  384. fp, err := GetManifestPath()
  385. if err != nil {
  386. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  387. return
  388. }
  389. walkFunc := func(path string, info os.FileInfo, _ error) error {
  390. if !info.IsDir() {
  391. dir, file := filepath.Split(path)
  392. dir = strings.Trim(strings.TrimPrefix(dir, fp), string(os.PathSeparator))
  393. tag := strings.Join([]string{dir, file}, ":")
  394. mp := ParseModelPath(tag)
  395. manifest, digest, err := GetManifest(mp)
  396. if err != nil {
  397. log.Printf("skipping file: %s", fp)
  398. return nil
  399. }
  400. models = append(models, api.ModelResponse{
  401. Name: mp.GetShortTagname(),
  402. Size: manifest.GetTotalSize(),
  403. Digest: digest,
  404. ModifiedAt: info.ModTime(),
  405. })
  406. }
  407. return nil
  408. }
  409. if err := filepath.Walk(fp, walkFunc); err != nil {
  410. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  411. return
  412. }
  413. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  414. }
  415. func CopyModelHandler(c *gin.Context) {
  416. var req api.CopyRequest
  417. if err := c.ShouldBindJSON(&req); err != nil {
  418. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  419. return
  420. }
  421. if err := CopyModel(req.Source, req.Destination); err != nil {
  422. if os.IsNotExist(err) {
  423. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  424. } else {
  425. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  426. }
  427. return
  428. }
  429. }
  430. var defaultAllowOrigins = []string{
  431. "localhost",
  432. "127.0.0.1",
  433. "0.0.0.0",
  434. }
  435. func Serve(ln net.Listener, allowOrigins []string) error {
  436. config := cors.DefaultConfig()
  437. config.AllowWildcard = true
  438. config.AllowOrigins = allowOrigins
  439. for _, allowOrigin := range defaultAllowOrigins {
  440. config.AllowOrigins = append(config.AllowOrigins,
  441. fmt.Sprintf("http://%s", allowOrigin),
  442. fmt.Sprintf("https://%s", allowOrigin),
  443. fmt.Sprintf("http://%s:*", allowOrigin),
  444. fmt.Sprintf("https://%s:*", allowOrigin),
  445. )
  446. }
  447. workDir, err := os.MkdirTemp("", "ollama")
  448. if err != nil {
  449. return err
  450. }
  451. defer os.RemoveAll(workDir)
  452. r := gin.Default()
  453. r.Use(
  454. cors.New(config),
  455. func(c *gin.Context) {
  456. c.Set("workDir", workDir)
  457. c.Next()
  458. },
  459. )
  460. r.POST("/api/pull", PullModelHandler)
  461. r.POST("/api/generate", GenerateHandler)
  462. r.POST("/api/embeddings", EmbeddingHandler)
  463. r.POST("/api/create", CreateModelHandler)
  464. r.POST("/api/push", PushModelHandler)
  465. r.POST("/api/copy", CopyModelHandler)
  466. r.DELETE("/api/delete", DeleteModelHandler)
  467. r.POST("/api/show", ShowModelHandler)
  468. for _, method := range []string{http.MethodGet, http.MethodHead} {
  469. r.Handle(method, "/", func(c *gin.Context) {
  470. c.String(http.StatusOK, "Ollama is running")
  471. })
  472. r.Handle(method, "/api/tags", ListModelsHandler)
  473. }
  474. log.Printf("Listening on %s (version %s)", ln.Addr(), version.Version)
  475. s := &http.Server{
  476. Handler: r,
  477. }
  478. // listen for a ctrl+c and stop any loaded llm
  479. signals := make(chan os.Signal, 1)
  480. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  481. go func() {
  482. <-signals
  483. if loaded.runner != nil {
  484. loaded.runner.Close()
  485. }
  486. os.RemoveAll(workDir)
  487. os.Exit(0)
  488. }()
  489. if runtime.GOOS == "linux" {
  490. // check compatibility to log warnings
  491. if _, err := llm.CheckVRAM(); err != nil {
  492. log.Printf("Warning: GPU support may not enabled, check you have installed install GPU drivers: %v", err)
  493. }
  494. }
  495. return s.Serve(ln)
  496. }
  497. func waitForStream(c *gin.Context, ch chan interface{}) {
  498. c.Header("Content-Type", "application/json")
  499. for resp := range ch {
  500. switch r := resp.(type) {
  501. case api.ProgressResponse:
  502. if r.Status == "success" {
  503. c.JSON(http.StatusOK, r)
  504. return
  505. }
  506. case gin.H:
  507. if errorMsg, ok := r["error"].(string); ok {
  508. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  509. return
  510. } else {
  511. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  512. return
  513. }
  514. default:
  515. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  516. return
  517. }
  518. }
  519. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  520. }
  521. func streamResponse(c *gin.Context, ch chan any) {
  522. c.Header("Content-Type", "application/x-ndjson")
  523. c.Stream(func(w io.Writer) bool {
  524. val, ok := <-ch
  525. if !ok {
  526. return false
  527. }
  528. bts, err := json.Marshal(val)
  529. if err != nil {
  530. log.Printf("streamResponse: json.Marshal failed with %s", err)
  531. return false
  532. }
  533. // Delineate chunks with new-line delimiter
  534. bts = append(bts, '\n')
  535. if _, err := w.Write(bts); err != nil {
  536. log.Printf("streamResponse: w.Write failed with %s", err)
  537. return false
  538. }
  539. return true
  540. })
  541. }