routes.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. package server
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/fs"
  10. "log"
  11. "net"
  12. "net/http"
  13. "os"
  14. "os/signal"
  15. "path/filepath"
  16. "reflect"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "syscall"
  22. "time"
  23. "github.com/gin-contrib/cors"
  24. "github.com/gin-gonic/gin"
  25. "github.com/jmorganca/ollama/api"
  26. "github.com/jmorganca/ollama/llm"
  27. "github.com/jmorganca/ollama/parser"
  28. "github.com/jmorganca/ollama/version"
  29. )
  30. var mode string = gin.DebugMode
  31. func init() {
  32. switch mode {
  33. case gin.DebugMode:
  34. case gin.ReleaseMode:
  35. case gin.TestMode:
  36. default:
  37. mode = gin.DebugMode
  38. }
  39. gin.SetMode(mode)
  40. }
  41. var loaded struct {
  42. mu sync.Mutex
  43. runner llm.LLM
  44. expireAt time.Time
  45. expireTimer *time.Timer
  46. *Model
  47. *api.Options
  48. }
  49. var defaultSessionDuration = 5 * time.Minute
  50. // 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
  51. func load(ctx context.Context, workDir string, model *Model, reqOpts map[string]interface{}, sessionDuration time.Duration) error {
  52. opts := api.DefaultOptions()
  53. if err := opts.FromMap(model.Options); err != nil {
  54. log.Printf("could not load model options: %v", err)
  55. return err
  56. }
  57. if err := opts.FromMap(reqOpts); err != nil {
  58. return err
  59. }
  60. // check if the loaded model is still running in a subprocess, in case something unexpected happened
  61. if loaded.runner != nil {
  62. if err := loaded.runner.Ping(ctx); err != nil {
  63. log.Print("loaded llm process not responding, closing now")
  64. // the subprocess is no longer running, so close it
  65. loaded.runner.Close()
  66. loaded.runner = nil
  67. loaded.Model = nil
  68. loaded.Options = nil
  69. }
  70. }
  71. needLoad := loaded.runner == nil || // is there a model loaded?
  72. loaded.ModelPath != model.ModelPath || // has the base model changed?
  73. !reflect.DeepEqual(loaded.AdapterPaths, model.AdapterPaths) || // have the adapters changed?
  74. !reflect.DeepEqual(loaded.Options.Runner, opts.Runner) // have the runner options changed?
  75. if needLoad {
  76. if loaded.runner != nil {
  77. log.Println("changing loaded model")
  78. loaded.runner.Close()
  79. loaded.runner = nil
  80. loaded.Model = nil
  81. loaded.Options = nil
  82. }
  83. llmRunner, err := llm.New(workDir, model.ModelPath, model.AdapterPaths, opts)
  84. if err != nil {
  85. // some older models are not compatible with newer versions of llama.cpp
  86. // show a generalized compatibility error until there is a better way to
  87. // check for model compatibility
  88. if strings.Contains(err.Error(), "failed to load model") {
  89. err = fmt.Errorf("%v: this model may be incompatible with your version of Ollama. If you previously pulled this model, try updating it by running `ollama pull %s`", err, model.ShortName)
  90. }
  91. return err
  92. }
  93. loaded.Model = model
  94. loaded.runner = llmRunner
  95. loaded.Options = &opts
  96. }
  97. // update options for the loaded llm
  98. // TODO(mxyng): this isn't thread safe, but it should be fine for now
  99. loaded.runner.SetOptions(opts)
  100. loaded.expireAt = time.Now().Add(sessionDuration)
  101. if loaded.expireTimer == nil {
  102. loaded.expireTimer = time.AfterFunc(sessionDuration, func() {
  103. loaded.mu.Lock()
  104. defer loaded.mu.Unlock()
  105. if time.Now().Before(loaded.expireAt) {
  106. return
  107. }
  108. if loaded.runner != nil {
  109. loaded.runner.Close()
  110. }
  111. loaded.runner = nil
  112. loaded.Model = nil
  113. loaded.Options = nil
  114. })
  115. }
  116. loaded.expireTimer.Reset(sessionDuration)
  117. return nil
  118. }
  119. func GenerateHandler(c *gin.Context) {
  120. loaded.mu.Lock()
  121. defer loaded.mu.Unlock()
  122. checkpointStart := time.Now()
  123. var req api.GenerateRequest
  124. err := c.ShouldBindJSON(&req)
  125. switch {
  126. case errors.Is(err, io.EOF):
  127. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  128. return
  129. case err != nil:
  130. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  131. return
  132. }
  133. // validate the request
  134. switch {
  135. case req.Model == "":
  136. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  137. return
  138. case len(req.Format) > 0 && req.Format != "json":
  139. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
  140. return
  141. case req.Raw && (req.Template != "" || req.System != "" || len(req.Context) > 0):
  142. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "raw mode does not support template, system, or context"})
  143. return
  144. }
  145. model, err := GetModel(req.Model)
  146. if err != nil {
  147. var pErr *fs.PathError
  148. if errors.As(err, &pErr) {
  149. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  150. return
  151. }
  152. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  153. return
  154. }
  155. workDir := c.GetString("workDir")
  156. // TODO: set this duration from the request if specified
  157. sessionDuration := defaultSessionDuration
  158. if err := load(c.Request.Context(), workDir, model, req.Options, sessionDuration); err != nil {
  159. if errors.Is(err, api.ErrInvalidOpts) {
  160. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  161. return
  162. }
  163. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  164. return
  165. }
  166. checkpointLoaded := time.Now()
  167. prompt := req.Prompt
  168. if !req.Raw {
  169. prompt, err = model.Prompt(req)
  170. if err != nil {
  171. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  172. return
  173. }
  174. }
  175. ch := make(chan any)
  176. go func() {
  177. defer close(ch)
  178. // an empty request loads the model
  179. if req.Prompt == "" && req.Template == "" && req.System == "" {
  180. ch <- api.GenerateResponse{CreatedAt: time.Now().UTC(), Model: req.Model, Done: true}
  181. return
  182. }
  183. fn := func(r api.GenerateResponse) {
  184. loaded.expireAt = time.Now().Add(sessionDuration)
  185. loaded.expireTimer.Reset(sessionDuration)
  186. r.Model = req.Model
  187. r.CreatedAt = time.Now().UTC()
  188. if r.Done {
  189. r.TotalDuration = time.Since(checkpointStart)
  190. r.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  191. }
  192. if req.Raw {
  193. // in raw mode the client must manage history on their own
  194. r.Context = nil
  195. }
  196. ch <- r
  197. }
  198. if err := loaded.runner.Predict(c.Request.Context(), req.Context, prompt, req.Format, fn); err != nil {
  199. ch <- gin.H{"error": err.Error()}
  200. }
  201. }()
  202. if req.Stream != nil && !*req.Stream {
  203. var response api.GenerateResponse
  204. generated := ""
  205. for resp := range ch {
  206. if r, ok := resp.(api.GenerateResponse); ok {
  207. generated += r.Response
  208. response = r
  209. } else {
  210. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  211. return
  212. }
  213. }
  214. response.Response = generated
  215. c.JSON(http.StatusOK, response)
  216. return
  217. }
  218. streamResponse(c, ch)
  219. }
  220. func EmbeddingHandler(c *gin.Context) {
  221. loaded.mu.Lock()
  222. defer loaded.mu.Unlock()
  223. var req api.EmbeddingRequest
  224. err := c.ShouldBindJSON(&req)
  225. switch {
  226. case errors.Is(err, io.EOF):
  227. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  228. return
  229. case err != nil:
  230. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  231. return
  232. }
  233. if req.Model == "" {
  234. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  235. return
  236. }
  237. model, err := GetModel(req.Model)
  238. if err != nil {
  239. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  240. return
  241. }
  242. workDir := c.GetString("workDir")
  243. if err := load(c.Request.Context(), workDir, model, req.Options, 5*time.Minute); err != nil {
  244. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  245. return
  246. }
  247. if !loaded.Options.EmbeddingOnly {
  248. c.JSON(http.StatusBadRequest, gin.H{"error": "embedding option must be set to true"})
  249. return
  250. }
  251. embedding, err := loaded.runner.Embedding(c.Request.Context(), req.Prompt)
  252. if err != nil {
  253. log.Printf("embedding generation failed: %v", err)
  254. c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
  255. return
  256. }
  257. resp := api.EmbeddingResponse{
  258. Embedding: embedding,
  259. }
  260. c.JSON(http.StatusOK, resp)
  261. }
  262. func PullModelHandler(c *gin.Context) {
  263. var req api.PullRequest
  264. err := c.ShouldBindJSON(&req)
  265. switch {
  266. case errors.Is(err, io.EOF):
  267. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  268. return
  269. case err != nil:
  270. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  271. return
  272. }
  273. if req.Name == "" {
  274. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  275. return
  276. }
  277. ch := make(chan any)
  278. go func() {
  279. defer close(ch)
  280. fn := func(r api.ProgressResponse) {
  281. ch <- r
  282. }
  283. regOpts := &RegistryOptions{
  284. Insecure: req.Insecure,
  285. }
  286. ctx, cancel := context.WithCancel(c.Request.Context())
  287. defer cancel()
  288. if err := PullModel(ctx, req.Name, regOpts, fn); err != nil {
  289. ch <- gin.H{"error": err.Error()}
  290. }
  291. }()
  292. if req.Stream != nil && !*req.Stream {
  293. waitForStream(c, ch)
  294. return
  295. }
  296. streamResponse(c, ch)
  297. }
  298. func PushModelHandler(c *gin.Context) {
  299. var req api.PushRequest
  300. err := c.ShouldBindJSON(&req)
  301. switch {
  302. case errors.Is(err, io.EOF):
  303. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  304. return
  305. case err != nil:
  306. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  307. return
  308. }
  309. if req.Name == "" {
  310. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  311. return
  312. }
  313. ch := make(chan any)
  314. go func() {
  315. defer close(ch)
  316. fn := func(r api.ProgressResponse) {
  317. ch <- r
  318. }
  319. regOpts := &RegistryOptions{
  320. Insecure: req.Insecure,
  321. }
  322. ctx, cancel := context.WithCancel(c.Request.Context())
  323. defer cancel()
  324. if err := PushModel(ctx, req.Name, regOpts, fn); err != nil {
  325. ch <- gin.H{"error": err.Error()}
  326. }
  327. }()
  328. if req.Stream != nil && !*req.Stream {
  329. waitForStream(c, ch)
  330. return
  331. }
  332. streamResponse(c, ch)
  333. }
  334. func CreateModelHandler(c *gin.Context) {
  335. var req api.CreateRequest
  336. err := c.ShouldBindJSON(&req)
  337. switch {
  338. case errors.Is(err, io.EOF):
  339. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  340. return
  341. case err != nil:
  342. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  343. return
  344. }
  345. if req.Name == "" {
  346. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  347. return
  348. }
  349. if req.Path == "" && req.Modelfile == "" {
  350. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
  351. return
  352. }
  353. var modelfile io.Reader = strings.NewReader(req.Modelfile)
  354. if req.Path != "" && req.Modelfile == "" {
  355. mf, err := os.Open(req.Path)
  356. if err != nil {
  357. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
  358. return
  359. }
  360. defer mf.Close()
  361. modelfile = mf
  362. }
  363. commands, err := parser.Parse(modelfile)
  364. if err != nil {
  365. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  366. return
  367. }
  368. ch := make(chan any)
  369. go func() {
  370. defer close(ch)
  371. fn := func(resp api.ProgressResponse) {
  372. ch <- resp
  373. }
  374. ctx, cancel := context.WithCancel(c.Request.Context())
  375. defer cancel()
  376. if err := CreateModel(ctx, req.Name, filepath.Dir(req.Path), commands, fn); err != nil {
  377. ch <- gin.H{"error": err.Error()}
  378. }
  379. }()
  380. if req.Stream != nil && !*req.Stream {
  381. waitForStream(c, ch)
  382. return
  383. }
  384. streamResponse(c, ch)
  385. }
  386. func DeleteModelHandler(c *gin.Context) {
  387. var req api.DeleteRequest
  388. err := c.ShouldBindJSON(&req)
  389. switch {
  390. case errors.Is(err, io.EOF):
  391. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  392. return
  393. case err != nil:
  394. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  395. return
  396. }
  397. if req.Name == "" {
  398. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  399. return
  400. }
  401. if err := DeleteModel(req.Name); err != nil {
  402. if os.IsNotExist(err) {
  403. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  404. } else {
  405. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  406. }
  407. return
  408. }
  409. manifestsPath, err := GetManifestPath()
  410. if err != nil {
  411. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  412. return
  413. }
  414. if err := PruneDirectory(manifestsPath); err != nil {
  415. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  416. return
  417. }
  418. c.JSON(http.StatusOK, nil)
  419. }
  420. func ShowModelHandler(c *gin.Context) {
  421. var req api.ShowRequest
  422. err := c.ShouldBindJSON(&req)
  423. switch {
  424. case errors.Is(err, io.EOF):
  425. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  426. return
  427. case err != nil:
  428. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  429. return
  430. }
  431. if req.Name == "" {
  432. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  433. return
  434. }
  435. resp, err := GetModelInfo(req.Name)
  436. if err != nil {
  437. if os.IsNotExist(err) {
  438. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  439. } else {
  440. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  441. }
  442. return
  443. }
  444. c.JSON(http.StatusOK, resp)
  445. }
  446. func GetModelInfo(name string) (*api.ShowResponse, error) {
  447. model, err := GetModel(name)
  448. if err != nil {
  449. return nil, err
  450. }
  451. resp := &api.ShowResponse{
  452. License: strings.Join(model.License, "\n"),
  453. System: model.System,
  454. Template: model.Template,
  455. }
  456. mf, err := ShowModelfile(model)
  457. if err != nil {
  458. return nil, err
  459. }
  460. resp.Modelfile = mf
  461. var params []string
  462. cs := 30
  463. for k, v := range model.Options {
  464. switch val := v.(type) {
  465. case string:
  466. params = append(params, fmt.Sprintf("%-*s %s", cs, k, val))
  467. case int:
  468. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(val)))
  469. case float64:
  470. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(val, 'f', 0, 64)))
  471. case bool:
  472. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(val)))
  473. case []interface{}:
  474. for _, nv := range val {
  475. switch nval := nv.(type) {
  476. case string:
  477. params = append(params, fmt.Sprintf("%-*s %s", cs, k, nval))
  478. case int:
  479. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(nval)))
  480. case float64:
  481. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(nval, 'f', 0, 64)))
  482. case bool:
  483. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(nval)))
  484. }
  485. }
  486. }
  487. }
  488. resp.Parameters = strings.Join(params, "\n")
  489. return resp, nil
  490. }
  491. func ListModelsHandler(c *gin.Context) {
  492. models := make([]api.ModelResponse, 0)
  493. fp, err := GetManifestPath()
  494. if err != nil {
  495. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  496. return
  497. }
  498. walkFunc := func(path string, info os.FileInfo, _ error) error {
  499. if !info.IsDir() {
  500. dir, file := filepath.Split(path)
  501. dir = strings.Trim(strings.TrimPrefix(dir, fp), string(os.PathSeparator))
  502. tag := strings.Join([]string{dir, file}, ":")
  503. mp := ParseModelPath(tag)
  504. manifest, digest, err := GetManifest(mp)
  505. if err != nil {
  506. log.Printf("skipping file: %s", fp)
  507. return nil
  508. }
  509. models = append(models, api.ModelResponse{
  510. Name: mp.GetShortTagname(),
  511. Size: manifest.GetTotalSize(),
  512. Digest: digest,
  513. ModifiedAt: info.ModTime(),
  514. })
  515. }
  516. return nil
  517. }
  518. if err := filepath.Walk(fp, walkFunc); err != nil {
  519. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  520. return
  521. }
  522. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  523. }
  524. func CopyModelHandler(c *gin.Context) {
  525. var req api.CopyRequest
  526. err := c.ShouldBindJSON(&req)
  527. switch {
  528. case errors.Is(err, io.EOF):
  529. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  530. return
  531. case err != nil:
  532. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  533. return
  534. }
  535. if req.Source == "" || req.Destination == "" {
  536. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
  537. return
  538. }
  539. if err := CopyModel(req.Source, req.Destination); err != nil {
  540. if os.IsNotExist(err) {
  541. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  542. } else {
  543. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  544. }
  545. return
  546. }
  547. }
  548. func HeadBlobHandler(c *gin.Context) {
  549. path, err := GetBlobsPath(c.Param("digest"))
  550. if err != nil {
  551. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  552. return
  553. }
  554. if _, err := os.Stat(path); err != nil {
  555. c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("blob %q not found", c.Param("digest"))})
  556. return
  557. }
  558. c.Status(http.StatusOK)
  559. }
  560. func CreateBlobHandler(c *gin.Context) {
  561. targetPath, err := GetBlobsPath(c.Param("digest"))
  562. if err != nil {
  563. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  564. return
  565. }
  566. hash := sha256.New()
  567. temp, err := os.CreateTemp(filepath.Dir(targetPath), c.Param("digest")+"-")
  568. if err != nil {
  569. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  570. return
  571. }
  572. defer temp.Close()
  573. defer os.Remove(temp.Name())
  574. if _, err := io.Copy(temp, io.TeeReader(c.Request.Body, hash)); err != nil {
  575. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  576. return
  577. }
  578. if fmt.Sprintf("sha256:%x", hash.Sum(nil)) != c.Param("digest") {
  579. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "digest does not match body"})
  580. return
  581. }
  582. if err := temp.Close(); err != nil {
  583. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  584. return
  585. }
  586. if err := os.Rename(temp.Name(), targetPath); err != nil {
  587. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  588. return
  589. }
  590. c.Status(http.StatusCreated)
  591. }
  592. var defaultAllowOrigins = []string{
  593. "localhost",
  594. "127.0.0.1",
  595. "0.0.0.0",
  596. }
  597. func Serve(ln net.Listener, allowOrigins []string) error {
  598. if noprune := os.Getenv("OLLAMA_NOPRUNE"); noprune == "" {
  599. // clean up unused layers and manifests
  600. if err := PruneLayers(); err != nil {
  601. return err
  602. }
  603. manifestsPath, err := GetManifestPath()
  604. if err != nil {
  605. return err
  606. }
  607. if err := PruneDirectory(manifestsPath); err != nil {
  608. return err
  609. }
  610. }
  611. config := cors.DefaultConfig()
  612. config.AllowWildcard = true
  613. config.AllowOrigins = allowOrigins
  614. for _, allowOrigin := range defaultAllowOrigins {
  615. config.AllowOrigins = append(config.AllowOrigins,
  616. fmt.Sprintf("http://%s", allowOrigin),
  617. fmt.Sprintf("https://%s", allowOrigin),
  618. fmt.Sprintf("http://%s:*", allowOrigin),
  619. fmt.Sprintf("https://%s:*", allowOrigin),
  620. )
  621. }
  622. workDir, err := os.MkdirTemp("", "ollama")
  623. if err != nil {
  624. return err
  625. }
  626. defer os.RemoveAll(workDir)
  627. r := gin.Default()
  628. r.Use(
  629. cors.New(config),
  630. func(c *gin.Context) {
  631. c.Set("workDir", workDir)
  632. c.Next()
  633. },
  634. )
  635. r.POST("/api/pull", PullModelHandler)
  636. r.POST("/api/generate", GenerateHandler)
  637. r.POST("/api/embeddings", EmbeddingHandler)
  638. r.POST("/api/create", CreateModelHandler)
  639. r.POST("/api/push", PushModelHandler)
  640. r.POST("/api/copy", CopyModelHandler)
  641. r.DELETE("/api/delete", DeleteModelHandler)
  642. r.POST("/api/show", ShowModelHandler)
  643. r.POST("/api/blobs/:digest", CreateBlobHandler)
  644. r.HEAD("/api/blobs/:digest", HeadBlobHandler)
  645. for _, method := range []string{http.MethodGet, http.MethodHead} {
  646. r.Handle(method, "/", func(c *gin.Context) {
  647. c.String(http.StatusOK, "Ollama is running")
  648. })
  649. r.Handle(method, "/api/tags", ListModelsHandler)
  650. }
  651. log.Printf("Listening on %s (version %s)", ln.Addr(), version.Version)
  652. s := &http.Server{
  653. Handler: r,
  654. }
  655. // listen for a ctrl+c and stop any loaded llm
  656. signals := make(chan os.Signal, 1)
  657. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  658. go func() {
  659. <-signals
  660. if loaded.runner != nil {
  661. loaded.runner.Close()
  662. }
  663. os.RemoveAll(workDir)
  664. os.Exit(0)
  665. }()
  666. if runtime.GOOS == "linux" {
  667. // check compatibility to log warnings
  668. if _, err := llm.CheckVRAM(); err != nil {
  669. log.Printf(err.Error())
  670. }
  671. }
  672. return s.Serve(ln)
  673. }
  674. func waitForStream(c *gin.Context, ch chan interface{}) {
  675. c.Header("Content-Type", "application/json")
  676. for resp := range ch {
  677. switch r := resp.(type) {
  678. case api.ProgressResponse:
  679. if r.Status == "success" {
  680. c.JSON(http.StatusOK, r)
  681. return
  682. }
  683. case gin.H:
  684. if errorMsg, ok := r["error"].(string); ok {
  685. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  686. return
  687. } else {
  688. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  689. return
  690. }
  691. default:
  692. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  693. return
  694. }
  695. }
  696. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  697. }
  698. func streamResponse(c *gin.Context, ch chan any) {
  699. c.Header("Content-Type", "application/x-ndjson")
  700. c.Stream(func(w io.Writer) bool {
  701. val, ok := <-ch
  702. if !ok {
  703. return false
  704. }
  705. bts, err := json.Marshal(val)
  706. if err != nil {
  707. log.Printf("streamResponse: json.Marshal failed with %s", err)
  708. return false
  709. }
  710. // Delineate chunks with new-line delimiter
  711. bts = append(bts, '\n')
  712. if _, err := w.Write(bts); err != nil {
  713. log.Printf("streamResponse: w.Write failed with %s", err)
  714. return false
  715. }
  716. return true
  717. })
  718. }