routes.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  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(c *gin.Context, modelName string, reqOpts map[string]interface{}, sessionDuration time.Duration) (*Model, error) {
  52. model, err := GetModel(modelName)
  53. if err != nil {
  54. return nil, err
  55. }
  56. workDir := c.GetString("workDir")
  57. opts := api.DefaultOptions()
  58. if err := opts.FromMap(model.Options); err != nil {
  59. log.Printf("could not load model options: %v", err)
  60. return nil, err
  61. }
  62. if err := opts.FromMap(reqOpts); err != nil {
  63. return nil, err
  64. }
  65. ctx := c.Request.Context()
  66. // check if the loaded model is still running in a subprocess, in case something unexpected happened
  67. if loaded.runner != nil {
  68. if err := loaded.runner.Ping(ctx); err != nil {
  69. log.Print("loaded llm process not responding, closing now")
  70. // the subprocess is no longer running, so close it
  71. loaded.runner.Close()
  72. loaded.runner = nil
  73. loaded.Model = nil
  74. loaded.Options = nil
  75. }
  76. }
  77. needLoad := loaded.runner == nil || // is there a model loaded?
  78. loaded.ModelPath != model.ModelPath || // has the base model changed?
  79. !reflect.DeepEqual(loaded.AdapterPaths, model.AdapterPaths) || // have the adapters changed?
  80. !reflect.DeepEqual(loaded.Options.Runner, opts.Runner) // have the runner options changed?
  81. if needLoad {
  82. if loaded.runner != nil {
  83. log.Println("changing loaded model")
  84. loaded.runner.Close()
  85. loaded.runner = nil
  86. loaded.Model = nil
  87. loaded.Options = nil
  88. }
  89. llmRunner, err := llm.New(workDir, model.ModelPath, model.AdapterPaths, opts)
  90. if err != nil {
  91. // some older models are not compatible with newer versions of llama.cpp
  92. // show a generalized compatibility error until there is a better way to
  93. // check for model compatibility
  94. if strings.Contains(err.Error(), "failed to load model") {
  95. 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)
  96. }
  97. return nil, err
  98. }
  99. loaded.Model = model
  100. loaded.runner = llmRunner
  101. loaded.Options = &opts
  102. }
  103. // update options for the loaded llm
  104. // TODO(mxyng): this isn't thread safe, but it should be fine for now
  105. loaded.runner.SetOptions(opts)
  106. loaded.expireAt = time.Now().Add(sessionDuration)
  107. if loaded.expireTimer == nil {
  108. loaded.expireTimer = time.AfterFunc(sessionDuration, func() {
  109. loaded.mu.Lock()
  110. defer loaded.mu.Unlock()
  111. if time.Now().Before(loaded.expireAt) {
  112. return
  113. }
  114. if loaded.runner != nil {
  115. loaded.runner.Close()
  116. }
  117. loaded.runner = nil
  118. loaded.Model = nil
  119. loaded.Options = nil
  120. })
  121. }
  122. loaded.expireTimer.Reset(sessionDuration)
  123. return model, nil
  124. }
  125. func GenerateHandler(c *gin.Context) {
  126. loaded.mu.Lock()
  127. defer loaded.mu.Unlock()
  128. checkpointStart := time.Now()
  129. var req api.GenerateRequest
  130. err := c.ShouldBindJSON(&req)
  131. switch {
  132. case errors.Is(err, io.EOF):
  133. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  134. return
  135. case err != nil:
  136. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  137. return
  138. }
  139. // validate the request
  140. switch {
  141. case req.Model == "":
  142. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  143. return
  144. case len(req.Format) > 0 && req.Format != "json":
  145. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
  146. return
  147. case req.Raw && (req.Template != "" || req.System != "" || len(req.Context) > 0):
  148. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "raw mode does not support template, system, or context"})
  149. return
  150. }
  151. sessionDuration := defaultSessionDuration
  152. model, err := load(c, req.Model, req.Options, sessionDuration)
  153. if err != nil {
  154. var pErr *fs.PathError
  155. switch {
  156. case errors.As(err, &pErr):
  157. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  158. case errors.Is(err, api.ErrInvalidOpts):
  159. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  160. default:
  161. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  162. }
  163. return
  164. }
  165. // an empty request loads the model
  166. if req.Prompt == "" && req.Template == "" && req.System == "" {
  167. c.JSON(http.StatusOK, api.GenerateResponse{CreatedAt: time.Now().UTC(), Model: req.Model, Done: true})
  168. return
  169. }
  170. checkpointLoaded := time.Now()
  171. var prompt string
  172. switch {
  173. case req.Raw:
  174. prompt = req.Prompt
  175. case req.Prompt != "":
  176. if req.Template != "" {
  177. // override the default model template
  178. model.Template = req.Template
  179. }
  180. var rebuild strings.Builder
  181. if req.Context != nil {
  182. // TODO: context is deprecated, at some point the context logic within this conditional should be removed
  183. prevCtx, err := loaded.runner.Decode(c.Request.Context(), req.Context)
  184. if err != nil {
  185. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  186. return
  187. }
  188. // Remove leading spaces from prevCtx if present
  189. prevCtx = strings.TrimPrefix(prevCtx, " ")
  190. rebuild.WriteString(prevCtx)
  191. }
  192. p, err := model.Prompt(PromptVars{
  193. System: req.System,
  194. Prompt: req.Prompt,
  195. First: len(req.Context) == 0,
  196. })
  197. if err != nil {
  198. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  199. return
  200. }
  201. rebuild.WriteString(p)
  202. prompt = rebuild.String()
  203. }
  204. ch := make(chan any)
  205. var generated strings.Builder
  206. go func() {
  207. defer close(ch)
  208. fn := func(r llm.PredictResult) {
  209. // Update model expiration
  210. loaded.expireAt = time.Now().Add(sessionDuration)
  211. loaded.expireTimer.Reset(sessionDuration)
  212. // Build up the full response
  213. if _, err := generated.WriteString(r.Content); err != nil {
  214. ch <- gin.H{"error": err.Error()}
  215. return
  216. }
  217. resp := api.GenerateResponse{
  218. Model: r.Model,
  219. CreatedAt: r.CreatedAt,
  220. Done: r.Done,
  221. Response: r.Content,
  222. Metrics: api.Metrics{
  223. TotalDuration: r.TotalDuration,
  224. LoadDuration: r.LoadDuration,
  225. PromptEvalCount: r.PromptEvalCount,
  226. PromptEvalDuration: r.PromptEvalDuration,
  227. EvalCount: r.EvalCount,
  228. EvalDuration: r.EvalDuration,
  229. },
  230. }
  231. if r.Done && !req.Raw {
  232. embd, err := loaded.runner.Encode(c.Request.Context(), req.Prompt+generated.String())
  233. if err != nil {
  234. ch <- gin.H{"error": err.Error()}
  235. return
  236. }
  237. resp.Context = embd
  238. }
  239. ch <- resp
  240. }
  241. // Start prediction
  242. predictReq := llm.PredictOpts{
  243. Model: model.Name,
  244. Prompt: prompt,
  245. Format: req.Format,
  246. CheckpointStart: checkpointStart,
  247. CheckpointLoaded: checkpointLoaded,
  248. }
  249. if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
  250. ch <- gin.H{"error": err.Error()}
  251. }
  252. }()
  253. if req.Stream != nil && !*req.Stream {
  254. // Wait for the channel to close
  255. var r api.GenerateResponse
  256. var sb strings.Builder
  257. for resp := range ch {
  258. var ok bool
  259. if r, ok = resp.(api.GenerateResponse); !ok {
  260. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  261. return
  262. }
  263. sb.WriteString(r.Response)
  264. }
  265. r.Response = sb.String()
  266. c.JSON(http.StatusOK, r)
  267. return
  268. }
  269. streamResponse(c, ch)
  270. }
  271. func EmbeddingHandler(c *gin.Context) {
  272. loaded.mu.Lock()
  273. defer loaded.mu.Unlock()
  274. var req api.EmbeddingRequest
  275. err := c.ShouldBindJSON(&req)
  276. switch {
  277. case errors.Is(err, io.EOF):
  278. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  279. return
  280. case err != nil:
  281. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  282. return
  283. }
  284. if req.Model == "" {
  285. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  286. return
  287. }
  288. sessionDuration := defaultSessionDuration
  289. _, err = load(c, req.Model, req.Options, sessionDuration)
  290. if err != nil {
  291. var pErr *fs.PathError
  292. switch {
  293. case errors.As(err, &pErr):
  294. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  295. case errors.Is(err, api.ErrInvalidOpts):
  296. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  297. default:
  298. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  299. }
  300. return
  301. }
  302. if !loaded.Options.EmbeddingOnly {
  303. c.JSON(http.StatusBadRequest, gin.H{"error": "embedding option must be set to true"})
  304. return
  305. }
  306. embedding, err := loaded.runner.Embedding(c.Request.Context(), req.Prompt)
  307. if err != nil {
  308. log.Printf("embedding generation failed: %v", err)
  309. c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
  310. return
  311. }
  312. resp := api.EmbeddingResponse{
  313. Embedding: embedding,
  314. }
  315. c.JSON(http.StatusOK, resp)
  316. }
  317. func PullModelHandler(c *gin.Context) {
  318. var req api.PullRequest
  319. err := c.ShouldBindJSON(&req)
  320. switch {
  321. case errors.Is(err, io.EOF):
  322. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  323. return
  324. case err != nil:
  325. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  326. return
  327. }
  328. if req.Name == "" {
  329. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  330. return
  331. }
  332. ch := make(chan any)
  333. go func() {
  334. defer close(ch)
  335. fn := func(r api.ProgressResponse) {
  336. ch <- r
  337. }
  338. regOpts := &RegistryOptions{
  339. Insecure: req.Insecure,
  340. }
  341. ctx, cancel := context.WithCancel(c.Request.Context())
  342. defer cancel()
  343. if err := PullModel(ctx, req.Name, regOpts, fn); err != nil {
  344. ch <- gin.H{"error": err.Error()}
  345. }
  346. }()
  347. if req.Stream != nil && !*req.Stream {
  348. waitForStream(c, ch)
  349. return
  350. }
  351. streamResponse(c, ch)
  352. }
  353. func PushModelHandler(c *gin.Context) {
  354. var req api.PushRequest
  355. err := c.ShouldBindJSON(&req)
  356. switch {
  357. case errors.Is(err, io.EOF):
  358. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  359. return
  360. case err != nil:
  361. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  362. return
  363. }
  364. if req.Name == "" {
  365. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  366. return
  367. }
  368. ch := make(chan any)
  369. go func() {
  370. defer close(ch)
  371. fn := func(r api.ProgressResponse) {
  372. ch <- r
  373. }
  374. regOpts := &RegistryOptions{
  375. Insecure: req.Insecure,
  376. }
  377. ctx, cancel := context.WithCancel(c.Request.Context())
  378. defer cancel()
  379. if err := PushModel(ctx, req.Name, regOpts, fn); err != nil {
  380. ch <- gin.H{"error": err.Error()}
  381. }
  382. }()
  383. if req.Stream != nil && !*req.Stream {
  384. waitForStream(c, ch)
  385. return
  386. }
  387. streamResponse(c, ch)
  388. }
  389. func CreateModelHandler(c *gin.Context) {
  390. var req api.CreateRequest
  391. err := c.ShouldBindJSON(&req)
  392. switch {
  393. case errors.Is(err, io.EOF):
  394. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  395. return
  396. case err != nil:
  397. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  398. return
  399. }
  400. if req.Name == "" {
  401. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  402. return
  403. }
  404. if err := ParseModelPath(req.Name).Validate(); err != nil {
  405. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  406. return
  407. }
  408. if req.Path == "" && req.Modelfile == "" {
  409. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
  410. return
  411. }
  412. var modelfile io.Reader = strings.NewReader(req.Modelfile)
  413. if req.Path != "" && req.Modelfile == "" {
  414. mf, err := os.Open(req.Path)
  415. if err != nil {
  416. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
  417. return
  418. }
  419. defer mf.Close()
  420. modelfile = mf
  421. }
  422. commands, err := parser.Parse(modelfile)
  423. if err != nil {
  424. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  425. return
  426. }
  427. ch := make(chan any)
  428. go func() {
  429. defer close(ch)
  430. fn := func(resp api.ProgressResponse) {
  431. ch <- resp
  432. }
  433. ctx, cancel := context.WithCancel(c.Request.Context())
  434. defer cancel()
  435. if err := CreateModel(ctx, req.Name, filepath.Dir(req.Path), commands, fn); err != nil {
  436. ch <- gin.H{"error": err.Error()}
  437. }
  438. }()
  439. if req.Stream != nil && !*req.Stream {
  440. waitForStream(c, ch)
  441. return
  442. }
  443. streamResponse(c, ch)
  444. }
  445. func DeleteModelHandler(c *gin.Context) {
  446. var req api.DeleteRequest
  447. err := c.ShouldBindJSON(&req)
  448. switch {
  449. case errors.Is(err, io.EOF):
  450. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  451. return
  452. case err != nil:
  453. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  454. return
  455. }
  456. if req.Name == "" {
  457. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  458. return
  459. }
  460. if err := DeleteModel(req.Name); err != nil {
  461. if os.IsNotExist(err) {
  462. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  463. } else {
  464. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  465. }
  466. return
  467. }
  468. manifestsPath, err := GetManifestPath()
  469. if err != nil {
  470. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  471. return
  472. }
  473. if err := PruneDirectory(manifestsPath); err != nil {
  474. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  475. return
  476. }
  477. c.JSON(http.StatusOK, nil)
  478. }
  479. func ShowModelHandler(c *gin.Context) {
  480. var req api.ShowRequest
  481. err := c.ShouldBindJSON(&req)
  482. switch {
  483. case errors.Is(err, io.EOF):
  484. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  485. return
  486. case err != nil:
  487. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  488. return
  489. }
  490. if req.Name == "" {
  491. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  492. return
  493. }
  494. resp, err := GetModelInfo(req.Name)
  495. if err != nil {
  496. if os.IsNotExist(err) {
  497. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  498. } else {
  499. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  500. }
  501. return
  502. }
  503. c.JSON(http.StatusOK, resp)
  504. }
  505. func GetModelInfo(name string) (*api.ShowResponse, error) {
  506. model, err := GetModel(name)
  507. if err != nil {
  508. return nil, err
  509. }
  510. resp := &api.ShowResponse{
  511. License: strings.Join(model.License, "\n"),
  512. System: model.System,
  513. Template: model.Template,
  514. }
  515. mf, err := ShowModelfile(model)
  516. if err != nil {
  517. return nil, err
  518. }
  519. resp.Modelfile = mf
  520. var params []string
  521. cs := 30
  522. for k, v := range model.Options {
  523. switch val := v.(type) {
  524. case string:
  525. params = append(params, fmt.Sprintf("%-*s %s", cs, k, val))
  526. case int:
  527. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(val)))
  528. case float64:
  529. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(val, 'f', 0, 64)))
  530. case bool:
  531. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(val)))
  532. case []interface{}:
  533. for _, nv := range val {
  534. switch nval := nv.(type) {
  535. case string:
  536. params = append(params, fmt.Sprintf("%-*s %s", cs, k, nval))
  537. case int:
  538. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(nval)))
  539. case float64:
  540. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(nval, 'f', 0, 64)))
  541. case bool:
  542. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(nval)))
  543. }
  544. }
  545. }
  546. }
  547. resp.Parameters = strings.Join(params, "\n")
  548. return resp, nil
  549. }
  550. func ListModelsHandler(c *gin.Context) {
  551. models := make([]api.ModelResponse, 0)
  552. fp, err := GetManifestPath()
  553. if err != nil {
  554. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  555. return
  556. }
  557. walkFunc := func(path string, info os.FileInfo, _ error) error {
  558. if !info.IsDir() {
  559. dir, file := filepath.Split(path)
  560. dir = strings.Trim(strings.TrimPrefix(dir, fp), string(os.PathSeparator))
  561. tag := strings.Join([]string{dir, file}, ":")
  562. mp := ParseModelPath(tag)
  563. manifest, digest, err := GetManifest(mp)
  564. if err != nil {
  565. log.Printf("skipping file: %s", fp)
  566. return nil
  567. }
  568. models = append(models, api.ModelResponse{
  569. Name: mp.GetShortTagname(),
  570. Size: manifest.GetTotalSize(),
  571. Digest: digest,
  572. ModifiedAt: info.ModTime(),
  573. })
  574. }
  575. return nil
  576. }
  577. if err := filepath.Walk(fp, walkFunc); err != nil {
  578. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  579. return
  580. }
  581. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  582. }
  583. func CopyModelHandler(c *gin.Context) {
  584. var req api.CopyRequest
  585. err := c.ShouldBindJSON(&req)
  586. switch {
  587. case errors.Is(err, io.EOF):
  588. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  589. return
  590. case err != nil:
  591. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  592. return
  593. }
  594. if req.Source == "" || req.Destination == "" {
  595. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
  596. return
  597. }
  598. if err := ParseModelPath(req.Destination).Validate(); err != nil {
  599. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  600. return
  601. }
  602. if err := CopyModel(req.Source, req.Destination); err != nil {
  603. if os.IsNotExist(err) {
  604. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  605. } else {
  606. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  607. }
  608. return
  609. }
  610. }
  611. func HeadBlobHandler(c *gin.Context) {
  612. path, err := GetBlobsPath(c.Param("digest"))
  613. if err != nil {
  614. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  615. return
  616. }
  617. if _, err := os.Stat(path); err != nil {
  618. c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("blob %q not found", c.Param("digest"))})
  619. return
  620. }
  621. c.Status(http.StatusOK)
  622. }
  623. func CreateBlobHandler(c *gin.Context) {
  624. targetPath, err := GetBlobsPath(c.Param("digest"))
  625. if err != nil {
  626. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  627. return
  628. }
  629. hash := sha256.New()
  630. temp, err := os.CreateTemp(filepath.Dir(targetPath), c.Param("digest")+"-")
  631. if err != nil {
  632. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  633. return
  634. }
  635. defer temp.Close()
  636. defer os.Remove(temp.Name())
  637. if _, err := io.Copy(temp, io.TeeReader(c.Request.Body, hash)); err != nil {
  638. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  639. return
  640. }
  641. if fmt.Sprintf("sha256:%x", hash.Sum(nil)) != c.Param("digest") {
  642. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "digest does not match body"})
  643. return
  644. }
  645. if err := temp.Close(); err != nil {
  646. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  647. return
  648. }
  649. if err := os.Rename(temp.Name(), targetPath); err != nil {
  650. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  651. return
  652. }
  653. c.Status(http.StatusCreated)
  654. }
  655. var defaultAllowOrigins = []string{
  656. "localhost",
  657. "127.0.0.1",
  658. "0.0.0.0",
  659. }
  660. func Serve(ln net.Listener, allowOrigins []string) error {
  661. if noprune := os.Getenv("OLLAMA_NOPRUNE"); noprune == "" {
  662. // clean up unused layers and manifests
  663. if err := PruneLayers(); err != nil {
  664. return err
  665. }
  666. manifestsPath, err := GetManifestPath()
  667. if err != nil {
  668. return err
  669. }
  670. if err := PruneDirectory(manifestsPath); err != nil {
  671. return err
  672. }
  673. }
  674. config := cors.DefaultConfig()
  675. config.AllowWildcard = true
  676. config.AllowOrigins = allowOrigins
  677. for _, allowOrigin := range defaultAllowOrigins {
  678. config.AllowOrigins = append(config.AllowOrigins,
  679. fmt.Sprintf("http://%s", allowOrigin),
  680. fmt.Sprintf("https://%s", allowOrigin),
  681. fmt.Sprintf("http://%s:*", allowOrigin),
  682. fmt.Sprintf("https://%s:*", allowOrigin),
  683. )
  684. }
  685. workDir, err := os.MkdirTemp("", "ollama")
  686. if err != nil {
  687. return err
  688. }
  689. defer os.RemoveAll(workDir)
  690. r := gin.Default()
  691. r.Use(
  692. cors.New(config),
  693. func(c *gin.Context) {
  694. c.Set("workDir", workDir)
  695. c.Next()
  696. },
  697. )
  698. r.POST("/api/pull", PullModelHandler)
  699. r.POST("/api/generate", GenerateHandler)
  700. r.POST("/api/chat", ChatHandler)
  701. r.POST("/api/embeddings", EmbeddingHandler)
  702. r.POST("/api/create", CreateModelHandler)
  703. r.POST("/api/push", PushModelHandler)
  704. r.POST("/api/copy", CopyModelHandler)
  705. r.DELETE("/api/delete", DeleteModelHandler)
  706. r.POST("/api/show", ShowModelHandler)
  707. r.POST("/api/blobs/:digest", CreateBlobHandler)
  708. r.HEAD("/api/blobs/:digest", HeadBlobHandler)
  709. for _, method := range []string{http.MethodGet, http.MethodHead} {
  710. r.Handle(method, "/", func(c *gin.Context) {
  711. c.String(http.StatusOK, "Ollama is running")
  712. })
  713. r.Handle(method, "/api/tags", ListModelsHandler)
  714. }
  715. log.Printf("Listening on %s (version %s)", ln.Addr(), version.Version)
  716. s := &http.Server{
  717. Handler: r,
  718. }
  719. // listen for a ctrl+c and stop any loaded llm
  720. signals := make(chan os.Signal, 1)
  721. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  722. go func() {
  723. <-signals
  724. if loaded.runner != nil {
  725. loaded.runner.Close()
  726. }
  727. os.RemoveAll(workDir)
  728. os.Exit(0)
  729. }()
  730. if runtime.GOOS == "linux" {
  731. // check compatibility to log warnings
  732. if _, err := llm.CheckVRAM(); err != nil {
  733. log.Printf(err.Error())
  734. }
  735. }
  736. return s.Serve(ln)
  737. }
  738. func waitForStream(c *gin.Context, ch chan interface{}) {
  739. c.Header("Content-Type", "application/json")
  740. for resp := range ch {
  741. switch r := resp.(type) {
  742. case api.ProgressResponse:
  743. if r.Status == "success" {
  744. c.JSON(http.StatusOK, r)
  745. return
  746. }
  747. case gin.H:
  748. if errorMsg, ok := r["error"].(string); ok {
  749. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  750. return
  751. } else {
  752. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  753. return
  754. }
  755. default:
  756. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  757. return
  758. }
  759. }
  760. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  761. }
  762. func streamResponse(c *gin.Context, ch chan any) {
  763. c.Header("Content-Type", "application/x-ndjson")
  764. c.Stream(func(w io.Writer) bool {
  765. val, ok := <-ch
  766. if !ok {
  767. return false
  768. }
  769. bts, err := json.Marshal(val)
  770. if err != nil {
  771. log.Printf("streamResponse: json.Marshal failed with %s", err)
  772. return false
  773. }
  774. // Delineate chunks with new-line delimiter
  775. bts = append(bts, '\n')
  776. if _, err := w.Write(bts); err != nil {
  777. log.Printf("streamResponse: w.Write failed with %s", err)
  778. return false
  779. }
  780. return true
  781. })
  782. }
  783. func ChatHandler(c *gin.Context) {
  784. loaded.mu.Lock()
  785. defer loaded.mu.Unlock()
  786. checkpointStart := time.Now()
  787. var req api.ChatRequest
  788. err := c.ShouldBindJSON(&req)
  789. switch {
  790. case errors.Is(err, io.EOF):
  791. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  792. return
  793. case err != nil:
  794. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  795. return
  796. }
  797. // validate the request
  798. switch {
  799. case req.Model == "":
  800. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  801. return
  802. case len(req.Format) > 0 && req.Format != "json":
  803. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
  804. return
  805. }
  806. sessionDuration := defaultSessionDuration
  807. model, err := load(c, req.Model, req.Options, sessionDuration)
  808. if err != nil {
  809. var pErr *fs.PathError
  810. switch {
  811. case errors.As(err, &pErr):
  812. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  813. case errors.Is(err, api.ErrInvalidOpts):
  814. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  815. default:
  816. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  817. }
  818. return
  819. }
  820. // an empty request loads the model
  821. if len(req.Messages) == 0 {
  822. c.JSON(http.StatusOK, api.ChatResponse{CreatedAt: time.Now().UTC(), Model: req.Model, Done: true})
  823. return
  824. }
  825. checkpointLoaded := time.Now()
  826. prompt, err := model.ChatPrompt(req.Messages)
  827. if err != nil {
  828. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  829. return
  830. }
  831. ch := make(chan any)
  832. go func() {
  833. defer close(ch)
  834. fn := func(r llm.PredictResult) {
  835. // Update model expiration
  836. loaded.expireAt = time.Now().Add(sessionDuration)
  837. loaded.expireTimer.Reset(sessionDuration)
  838. resp := api.ChatResponse{
  839. Model: r.Model,
  840. CreatedAt: r.CreatedAt,
  841. Done: r.Done,
  842. Metrics: api.Metrics{
  843. TotalDuration: r.TotalDuration,
  844. LoadDuration: r.LoadDuration,
  845. PromptEvalCount: r.PromptEvalCount,
  846. PromptEvalDuration: r.PromptEvalDuration,
  847. EvalCount: r.EvalCount,
  848. EvalDuration: r.EvalDuration,
  849. },
  850. }
  851. if !r.Done {
  852. resp.Message = &api.Message{Role: "assistant", Content: r.Content}
  853. }
  854. ch <- resp
  855. }
  856. // Start prediction
  857. predictReq := llm.PredictOpts{
  858. Model: model.Name,
  859. Prompt: prompt,
  860. Format: req.Format,
  861. CheckpointStart: checkpointStart,
  862. CheckpointLoaded: checkpointLoaded,
  863. }
  864. if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
  865. ch <- gin.H{"error": err.Error()}
  866. }
  867. }()
  868. if req.Stream != nil && !*req.Stream {
  869. // Wait for the channel to close
  870. var r api.ChatResponse
  871. var sb strings.Builder
  872. for resp := range ch {
  873. var ok bool
  874. if r, ok = resp.(api.ChatResponse); !ok {
  875. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  876. return
  877. }
  878. if r.Message != nil {
  879. sb.WriteString(r.Message.Content)
  880. }
  881. }
  882. r.Message = &api.Message{Role: "assistant", Content: sb.String()}
  883. c.JSON(http.StatusOK, r)
  884. return
  885. }
  886. streamResponse(c, ch)
  887. }