routes.go 29 KB

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