routes.go 26 KB

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