routes.go 15 KB

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