routes.go 32 KB

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