routes.go 31 KB

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