routes.go 26 KB

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