routes.go 32 KB

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