routes.go 29 KB

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