routes.go 31 KB

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