routes.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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 err := ParseModelPath(req.Name).Validate(); err != nil {
  350. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  351. return
  352. }
  353. if req.Path == "" && req.Modelfile == "" {
  354. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
  355. return
  356. }
  357. var modelfile io.Reader = strings.NewReader(req.Modelfile)
  358. if req.Path != "" && req.Modelfile == "" {
  359. mf, err := os.Open(req.Path)
  360. if err != nil {
  361. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
  362. return
  363. }
  364. defer mf.Close()
  365. modelfile = mf
  366. }
  367. commands, err := parser.Parse(modelfile)
  368. if err != nil {
  369. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  370. return
  371. }
  372. ch := make(chan any)
  373. go func() {
  374. defer close(ch)
  375. fn := func(resp api.ProgressResponse) {
  376. ch <- resp
  377. }
  378. ctx, cancel := context.WithCancel(c.Request.Context())
  379. defer cancel()
  380. if err := CreateModel(ctx, req.Name, filepath.Dir(req.Path), commands, fn); err != nil {
  381. ch <- gin.H{"error": err.Error()}
  382. }
  383. }()
  384. if req.Stream != nil && !*req.Stream {
  385. waitForStream(c, ch)
  386. return
  387. }
  388. streamResponse(c, ch)
  389. }
  390. func DeleteModelHandler(c *gin.Context) {
  391. var req api.DeleteRequest
  392. err := c.ShouldBindJSON(&req)
  393. switch {
  394. case errors.Is(err, io.EOF):
  395. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  396. return
  397. case err != nil:
  398. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  399. return
  400. }
  401. if req.Name == "" {
  402. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  403. return
  404. }
  405. if err := DeleteModel(req.Name); err != nil {
  406. if os.IsNotExist(err) {
  407. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  408. } else {
  409. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  410. }
  411. return
  412. }
  413. manifestsPath, err := GetManifestPath()
  414. if err != nil {
  415. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  416. return
  417. }
  418. if err := PruneDirectory(manifestsPath); err != nil {
  419. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  420. return
  421. }
  422. c.JSON(http.StatusOK, nil)
  423. }
  424. func ShowModelHandler(c *gin.Context) {
  425. var req api.ShowRequest
  426. err := c.ShouldBindJSON(&req)
  427. switch {
  428. case errors.Is(err, io.EOF):
  429. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  430. return
  431. case err != nil:
  432. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  433. return
  434. }
  435. if req.Name == "" {
  436. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  437. return
  438. }
  439. resp, err := GetModelInfo(req.Name)
  440. if err != nil {
  441. if os.IsNotExist(err) {
  442. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  443. } else {
  444. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  445. }
  446. return
  447. }
  448. c.JSON(http.StatusOK, resp)
  449. }
  450. func GetModelInfo(name string) (*api.ShowResponse, error) {
  451. model, err := GetModel(name)
  452. if err != nil {
  453. return nil, err
  454. }
  455. resp := &api.ShowResponse{
  456. License: strings.Join(model.License, "\n"),
  457. System: model.System,
  458. Template: model.Template,
  459. }
  460. mf, err := ShowModelfile(model)
  461. if err != nil {
  462. return nil, err
  463. }
  464. resp.Modelfile = mf
  465. var params []string
  466. cs := 30
  467. for k, v := range model.Options {
  468. switch val := v.(type) {
  469. case string:
  470. params = append(params, fmt.Sprintf("%-*s %s", cs, k, val))
  471. case int:
  472. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(val)))
  473. case float64:
  474. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(val, 'f', 0, 64)))
  475. case bool:
  476. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(val)))
  477. case []interface{}:
  478. for _, nv := range val {
  479. switch nval := nv.(type) {
  480. case string:
  481. params = append(params, fmt.Sprintf("%-*s %s", cs, k, nval))
  482. case int:
  483. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(nval)))
  484. case float64:
  485. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(nval, 'f', 0, 64)))
  486. case bool:
  487. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(nval)))
  488. }
  489. }
  490. }
  491. }
  492. resp.Parameters = strings.Join(params, "\n")
  493. return resp, nil
  494. }
  495. func ListModelsHandler(c *gin.Context) {
  496. models := make([]api.ModelResponse, 0)
  497. fp, err := GetManifestPath()
  498. if err != nil {
  499. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  500. return
  501. }
  502. walkFunc := func(path string, info os.FileInfo, _ error) error {
  503. if !info.IsDir() {
  504. dir, file := filepath.Split(path)
  505. dir = strings.Trim(strings.TrimPrefix(dir, fp), string(os.PathSeparator))
  506. tag := strings.Join([]string{dir, file}, ":")
  507. mp := ParseModelPath(tag)
  508. manifest, digest, err := GetManifest(mp)
  509. if err != nil {
  510. log.Printf("skipping file: %s", fp)
  511. return nil
  512. }
  513. models = append(models, api.ModelResponse{
  514. Name: mp.GetShortTagname(),
  515. Size: manifest.GetTotalSize(),
  516. Digest: digest,
  517. ModifiedAt: info.ModTime(),
  518. })
  519. }
  520. return nil
  521. }
  522. if err := filepath.Walk(fp, walkFunc); err != nil {
  523. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  524. return
  525. }
  526. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  527. }
  528. func CopyModelHandler(c *gin.Context) {
  529. var req api.CopyRequest
  530. err := c.ShouldBindJSON(&req)
  531. switch {
  532. case errors.Is(err, io.EOF):
  533. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  534. return
  535. case err != nil:
  536. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  537. return
  538. }
  539. if req.Source == "" || req.Destination == "" {
  540. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
  541. return
  542. }
  543. if err := ParseModelPath(req.Destination).Validate(); err != nil {
  544. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  545. return
  546. }
  547. if err := CopyModel(req.Source, req.Destination); err != nil {
  548. if os.IsNotExist(err) {
  549. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  550. } else {
  551. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  552. }
  553. return
  554. }
  555. }
  556. func HeadBlobHandler(c *gin.Context) {
  557. path, err := GetBlobsPath(c.Param("digest"))
  558. if err != nil {
  559. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  560. return
  561. }
  562. if _, err := os.Stat(path); err != nil {
  563. c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("blob %q not found", c.Param("digest"))})
  564. return
  565. }
  566. c.Status(http.StatusOK)
  567. }
  568. func CreateBlobHandler(c *gin.Context) {
  569. targetPath, err := GetBlobsPath(c.Param("digest"))
  570. if err != nil {
  571. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  572. return
  573. }
  574. hash := sha256.New()
  575. temp, err := os.CreateTemp(filepath.Dir(targetPath), c.Param("digest")+"-")
  576. if err != nil {
  577. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  578. return
  579. }
  580. defer temp.Close()
  581. defer os.Remove(temp.Name())
  582. if _, err := io.Copy(temp, io.TeeReader(c.Request.Body, hash)); err != nil {
  583. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  584. return
  585. }
  586. if fmt.Sprintf("sha256:%x", hash.Sum(nil)) != c.Param("digest") {
  587. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "digest does not match body"})
  588. return
  589. }
  590. if err := temp.Close(); err != nil {
  591. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  592. return
  593. }
  594. if err := os.Rename(temp.Name(), targetPath); err != nil {
  595. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  596. return
  597. }
  598. c.Status(http.StatusCreated)
  599. }
  600. var defaultAllowOrigins = []string{
  601. "localhost",
  602. "127.0.0.1",
  603. "0.0.0.0",
  604. }
  605. func Serve(ln net.Listener, allowOrigins []string) error {
  606. if noprune := os.Getenv("OLLAMA_NOPRUNE"); noprune == "" {
  607. // clean up unused layers and manifests
  608. if err := PruneLayers(); err != nil {
  609. return err
  610. }
  611. manifestsPath, err := GetManifestPath()
  612. if err != nil {
  613. return err
  614. }
  615. if err := PruneDirectory(manifestsPath); err != nil {
  616. return err
  617. }
  618. }
  619. config := cors.DefaultConfig()
  620. config.AllowWildcard = true
  621. config.AllowOrigins = allowOrigins
  622. for _, allowOrigin := range defaultAllowOrigins {
  623. config.AllowOrigins = append(config.AllowOrigins,
  624. fmt.Sprintf("http://%s", allowOrigin),
  625. fmt.Sprintf("https://%s", allowOrigin),
  626. fmt.Sprintf("http://%s:*", allowOrigin),
  627. fmt.Sprintf("https://%s:*", allowOrigin),
  628. )
  629. }
  630. workDir, err := os.MkdirTemp("", "ollama")
  631. if err != nil {
  632. return err
  633. }
  634. defer os.RemoveAll(workDir)
  635. r := gin.Default()
  636. r.Use(
  637. cors.New(config),
  638. func(c *gin.Context) {
  639. c.Set("workDir", workDir)
  640. c.Next()
  641. },
  642. )
  643. r.POST("/api/pull", PullModelHandler)
  644. r.POST("/api/generate", GenerateHandler)
  645. r.POST("/api/embeddings", EmbeddingHandler)
  646. r.POST("/api/create", CreateModelHandler)
  647. r.POST("/api/push", PushModelHandler)
  648. r.POST("/api/copy", CopyModelHandler)
  649. r.DELETE("/api/delete", DeleteModelHandler)
  650. r.POST("/api/show", ShowModelHandler)
  651. r.POST("/api/blobs/:digest", CreateBlobHandler)
  652. r.HEAD("/api/blobs/:digest", HeadBlobHandler)
  653. for _, method := range []string{http.MethodGet, http.MethodHead} {
  654. r.Handle(method, "/", func(c *gin.Context) {
  655. c.String(http.StatusOK, "Ollama is running")
  656. })
  657. r.Handle(method, "/api/tags", ListModelsHandler)
  658. }
  659. log.Printf("Listening on %s (version %s)", ln.Addr(), version.Version)
  660. s := &http.Server{
  661. Handler: r,
  662. }
  663. // listen for a ctrl+c and stop any loaded llm
  664. signals := make(chan os.Signal, 1)
  665. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  666. go func() {
  667. <-signals
  668. if loaded.runner != nil {
  669. loaded.runner.Close()
  670. }
  671. os.RemoveAll(workDir)
  672. os.Exit(0)
  673. }()
  674. if runtime.GOOS == "linux" {
  675. // check compatibility to log warnings
  676. if _, err := llm.CheckVRAM(); err != nil {
  677. log.Printf(err.Error())
  678. }
  679. }
  680. return s.Serve(ln)
  681. }
  682. func waitForStream(c *gin.Context, ch chan interface{}) {
  683. c.Header("Content-Type", "application/json")
  684. for resp := range ch {
  685. switch r := resp.(type) {
  686. case api.ProgressResponse:
  687. if r.Status == "success" {
  688. c.JSON(http.StatusOK, r)
  689. return
  690. }
  691. case gin.H:
  692. if errorMsg, ok := r["error"].(string); ok {
  693. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  694. return
  695. } else {
  696. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  697. return
  698. }
  699. default:
  700. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  701. return
  702. }
  703. }
  704. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  705. }
  706. func streamResponse(c *gin.Context, ch chan any) {
  707. c.Header("Content-Type", "application/x-ndjson")
  708. c.Stream(func(w io.Writer) bool {
  709. val, ok := <-ch
  710. if !ok {
  711. return false
  712. }
  713. bts, err := json.Marshal(val)
  714. if err != nil {
  715. log.Printf("streamResponse: json.Marshal failed with %s", err)
  716. return false
  717. }
  718. // Delineate chunks with new-line delimiter
  719. bts = append(bts, '\n')
  720. if _, err := w.Write(bts); err != nil {
  721. log.Printf("streamResponse: w.Write failed with %s", err)
  722. return false
  723. }
  724. return true
  725. })
  726. }