routes.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346
  1. package server
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/fs"
  9. "log/slog"
  10. "math"
  11. "net"
  12. "net/http"
  13. "net/netip"
  14. "os"
  15. "os/signal"
  16. "path/filepath"
  17. "strconv"
  18. "strings"
  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/ollama/ollama/api"
  25. "github.com/ollama/ollama/gpu"
  26. "github.com/ollama/ollama/llm"
  27. "github.com/ollama/ollama/openai"
  28. "github.com/ollama/ollama/parser"
  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. err := c.ShouldBindJSON(&req)
  445. switch {
  446. case errors.Is(err, io.EOF):
  447. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  448. return
  449. case err != nil:
  450. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  451. return
  452. }
  453. var model string
  454. if req.Model != "" {
  455. model = req.Model
  456. } else if req.Name != "" {
  457. model = req.Name
  458. } else {
  459. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  460. return
  461. }
  462. if err := ParseModelPath(model).Validate(); err != nil {
  463. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  464. return
  465. }
  466. if req.Path == "" && req.Modelfile == "" {
  467. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
  468. return
  469. }
  470. var modelfile io.Reader = strings.NewReader(req.Modelfile)
  471. if req.Path != "" && req.Modelfile == "" {
  472. mf, err := os.Open(req.Path)
  473. if err != nil {
  474. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
  475. return
  476. }
  477. defer mf.Close()
  478. modelfile = mf
  479. }
  480. commands, err := parser.Parse(modelfile)
  481. if err != nil {
  482. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  483. return
  484. }
  485. ch := make(chan any)
  486. go func() {
  487. defer close(ch)
  488. fn := func(resp api.ProgressResponse) {
  489. ch <- resp
  490. }
  491. ctx, cancel := context.WithCancel(c.Request.Context())
  492. defer cancel()
  493. if err := CreateModel(ctx, model, filepath.Dir(req.Path), strings.ToUpper(req.Quantization), commands, fn); err != nil {
  494. ch <- gin.H{"error": err.Error()}
  495. }
  496. }()
  497. if req.Stream != nil && !*req.Stream {
  498. waitForStream(c, ch)
  499. return
  500. }
  501. streamResponse(c, ch)
  502. }
  503. func (s *Server) DeleteModelHandler(c *gin.Context) {
  504. var req api.DeleteRequest
  505. err := c.ShouldBindJSON(&req)
  506. switch {
  507. case errors.Is(err, io.EOF):
  508. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  509. return
  510. case err != nil:
  511. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  512. return
  513. }
  514. var model string
  515. if req.Model != "" {
  516. model = req.Model
  517. } else if req.Name != "" {
  518. model = req.Name
  519. } else {
  520. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  521. return
  522. }
  523. if err := DeleteModel(model); err != nil {
  524. if os.IsNotExist(err) {
  525. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", model)})
  526. } else {
  527. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  528. }
  529. return
  530. }
  531. manifestsPath, err := GetManifestPath()
  532. if err != nil {
  533. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  534. return
  535. }
  536. if err := PruneDirectory(manifestsPath); err != nil {
  537. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  538. return
  539. }
  540. c.JSON(http.StatusOK, nil)
  541. }
  542. func (s *Server) ShowModelHandler(c *gin.Context) {
  543. var req api.ShowRequest
  544. err := c.ShouldBindJSON(&req)
  545. switch {
  546. case errors.Is(err, io.EOF):
  547. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  548. return
  549. case err != nil:
  550. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  551. return
  552. }
  553. if req.Model != "" {
  554. // noop
  555. } else if req.Name != "" {
  556. req.Model = req.Name
  557. } else {
  558. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  559. return
  560. }
  561. resp, err := GetModelInfo(req)
  562. if err != nil {
  563. if os.IsNotExist(err) {
  564. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
  565. } else {
  566. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  567. }
  568. return
  569. }
  570. c.JSON(http.StatusOK, resp)
  571. }
  572. func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
  573. model, err := GetModel(req.Model)
  574. if err != nil {
  575. return nil, err
  576. }
  577. modelDetails := api.ModelDetails{
  578. ParentModel: model.ParentModel,
  579. Format: model.Config.ModelFormat,
  580. Family: model.Config.ModelFamily,
  581. Families: model.Config.ModelFamilies,
  582. ParameterSize: model.Config.ModelType,
  583. QuantizationLevel: model.Config.FileType,
  584. }
  585. if req.System != "" {
  586. model.System = req.System
  587. }
  588. if req.Template != "" {
  589. model.Template = req.Template
  590. }
  591. msgs := make([]api.Message, 0)
  592. for _, msg := range model.Messages {
  593. msgs = append(msgs, api.Message{Role: msg.Role, Content: msg.Content})
  594. }
  595. resp := &api.ShowResponse{
  596. License: strings.Join(model.License, "\n"),
  597. System: model.System,
  598. Template: model.Template,
  599. Details: modelDetails,
  600. Messages: msgs,
  601. }
  602. var params []string
  603. cs := 30
  604. for k, v := range model.Options {
  605. switch val := v.(type) {
  606. case []interface{}:
  607. for _, nv := range val {
  608. params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
  609. }
  610. default:
  611. params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
  612. }
  613. }
  614. resp.Parameters = strings.Join(params, "\n")
  615. for k, v := range req.Options {
  616. if _, ok := req.Options[k]; ok {
  617. model.Options[k] = v
  618. }
  619. }
  620. var sb strings.Builder
  621. fmt.Fprintln(&sb, "# Modelfile generate by \"ollama show\"")
  622. fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
  623. fmt.Fprintf(&sb, "# FROM %s\n\n", model.ShortName)
  624. fmt.Fprint(&sb, parser.Format(model.Commands()))
  625. resp.Modelfile = sb.String()
  626. return resp, nil
  627. }
  628. func (s *Server) ListModelsHandler(c *gin.Context) {
  629. models := make([]api.ModelResponse, 0)
  630. manifestsPath, err := GetManifestPath()
  631. if err != nil {
  632. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  633. return
  634. }
  635. modelResponse := func(modelName string) (api.ModelResponse, error) {
  636. model, err := GetModel(modelName)
  637. if err != nil {
  638. return api.ModelResponse{}, err
  639. }
  640. modelDetails := api.ModelDetails{
  641. Format: model.Config.ModelFormat,
  642. Family: model.Config.ModelFamily,
  643. Families: model.Config.ModelFamilies,
  644. ParameterSize: model.Config.ModelType,
  645. QuantizationLevel: model.Config.FileType,
  646. }
  647. return api.ModelResponse{
  648. Model: model.ShortName,
  649. Name: model.ShortName,
  650. Size: model.Size,
  651. Digest: model.Digest,
  652. Details: modelDetails,
  653. }, nil
  654. }
  655. walkFunc := func(path string, info os.FileInfo, _ error) error {
  656. if !info.IsDir() {
  657. path, tag := filepath.Split(path)
  658. model := strings.Trim(strings.TrimPrefix(path, manifestsPath), string(os.PathSeparator))
  659. modelPath := strings.Join([]string{model, tag}, ":")
  660. canonicalModelPath := strings.ReplaceAll(modelPath, string(os.PathSeparator), "/")
  661. resp, err := modelResponse(canonicalModelPath)
  662. if err != nil {
  663. slog.Info(fmt.Sprintf("skipping file: %s", canonicalModelPath))
  664. // nolint: nilerr
  665. return nil
  666. }
  667. resp.ModifiedAt = info.ModTime()
  668. models = append(models, resp)
  669. }
  670. return nil
  671. }
  672. if err := filepath.Walk(manifestsPath, walkFunc); err != nil {
  673. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  674. return
  675. }
  676. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  677. }
  678. func (s *Server) CopyModelHandler(c *gin.Context) {
  679. var r api.CopyRequest
  680. if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
  681. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  682. return
  683. } else if err != nil {
  684. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  685. return
  686. }
  687. src := model.ParseName(r.Source)
  688. if !src.IsValid() {
  689. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("source %q is invalid", r.Source)})
  690. return
  691. }
  692. dst := model.ParseName(r.Destination)
  693. if !dst.IsValid() {
  694. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("destination %q is invalid", r.Source)})
  695. return
  696. }
  697. if err := CopyModel(src, dst); errors.Is(err, os.ErrNotExist) {
  698. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model %q not found", r.Source)})
  699. } else if err != nil {
  700. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  701. }
  702. }
  703. func (s *Server) HeadBlobHandler(c *gin.Context) {
  704. path, err := GetBlobsPath(c.Param("digest"))
  705. if err != nil {
  706. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  707. return
  708. }
  709. if _, err := os.Stat(path); err != nil {
  710. c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("blob %q not found", c.Param("digest"))})
  711. return
  712. }
  713. c.Status(http.StatusOK)
  714. }
  715. func (s *Server) CreateBlobHandler(c *gin.Context) {
  716. path, err := GetBlobsPath(c.Param("digest"))
  717. if err != nil {
  718. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  719. return
  720. }
  721. _, err = os.Stat(path)
  722. switch {
  723. case errors.Is(err, os.ErrNotExist):
  724. // noop
  725. case err != nil:
  726. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  727. return
  728. default:
  729. c.Status(http.StatusOK)
  730. return
  731. }
  732. layer, err := NewLayer(c.Request.Body, "")
  733. if err != nil {
  734. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  735. return
  736. }
  737. if layer.Digest != c.Param("digest") {
  738. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("digest mismatch, expected %q, got %q", c.Param("digest"), layer.Digest)})
  739. return
  740. }
  741. c.Status(http.StatusCreated)
  742. }
  743. var defaultAllowOrigins = []string{
  744. "localhost",
  745. "127.0.0.1",
  746. "0.0.0.0",
  747. }
  748. func isLocalIP(ip netip.Addr) bool {
  749. if interfaces, err := net.Interfaces(); err == nil {
  750. for _, iface := range interfaces {
  751. addrs, err := iface.Addrs()
  752. if err != nil {
  753. continue
  754. }
  755. for _, a := range addrs {
  756. if parsed, _, err := net.ParseCIDR(a.String()); err == nil {
  757. if parsed.String() == ip.String() {
  758. return true
  759. }
  760. }
  761. }
  762. }
  763. }
  764. return false
  765. }
  766. func allowedHost(host string) bool {
  767. if host == "" || host == "localhost" {
  768. return true
  769. }
  770. if hostname, err := os.Hostname(); err == nil && host == hostname {
  771. return true
  772. }
  773. var tlds = []string{
  774. "localhost",
  775. "local",
  776. "internal",
  777. }
  778. // check if the host is a local TLD
  779. for _, tld := range tlds {
  780. if strings.HasSuffix(host, "."+tld) {
  781. return true
  782. }
  783. }
  784. return false
  785. }
  786. func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
  787. return func(c *gin.Context) {
  788. if addr == nil {
  789. c.Next()
  790. return
  791. }
  792. if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
  793. c.Next()
  794. return
  795. }
  796. host, _, err := net.SplitHostPort(c.Request.Host)
  797. if err != nil {
  798. host = c.Request.Host
  799. }
  800. if addr, err := netip.ParseAddr(host); err == nil {
  801. if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
  802. c.Next()
  803. return
  804. }
  805. }
  806. if allowedHost(host) {
  807. c.Next()
  808. return
  809. }
  810. c.AbortWithStatus(http.StatusForbidden)
  811. }
  812. }
  813. func (s *Server) GenerateRoutes() http.Handler {
  814. config := cors.DefaultConfig()
  815. config.AllowWildcard = true
  816. config.AllowBrowserExtensions = true
  817. if allowedOrigins := strings.Trim(os.Getenv("OLLAMA_ORIGINS"), "\"'"); allowedOrigins != "" {
  818. config.AllowOrigins = strings.Split(allowedOrigins, ",")
  819. }
  820. for _, allowOrigin := range defaultAllowOrigins {
  821. config.AllowOrigins = append(config.AllowOrigins,
  822. fmt.Sprintf("http://%s", allowOrigin),
  823. fmt.Sprintf("https://%s", allowOrigin),
  824. fmt.Sprintf("http://%s:*", allowOrigin),
  825. fmt.Sprintf("https://%s:*", allowOrigin),
  826. )
  827. }
  828. r := gin.Default()
  829. r.Use(
  830. cors.New(config),
  831. allowedHostsMiddleware(s.addr),
  832. )
  833. r.POST("/api/pull", s.PullModelHandler)
  834. r.POST("/api/generate", s.GenerateHandler)
  835. r.POST("/api/chat", s.ChatHandler)
  836. r.POST("/api/embeddings", s.EmbeddingsHandler)
  837. r.POST("/api/create", s.CreateModelHandler)
  838. r.POST("/api/push", s.PushModelHandler)
  839. r.POST("/api/copy", s.CopyModelHandler)
  840. r.DELETE("/api/delete", s.DeleteModelHandler)
  841. r.POST("/api/show", s.ShowModelHandler)
  842. r.POST("/api/blobs/:digest", s.CreateBlobHandler)
  843. r.HEAD("/api/blobs/:digest", s.HeadBlobHandler)
  844. // Compatibility endpoints
  845. r.POST("/v1/chat/completions", openai.Middleware(), s.ChatHandler)
  846. for _, method := range []string{http.MethodGet, http.MethodHead} {
  847. r.Handle(method, "/", func(c *gin.Context) {
  848. c.String(http.StatusOK, "Ollama is running")
  849. })
  850. r.Handle(method, "/api/tags", s.ListModelsHandler)
  851. r.Handle(method, "/api/version", func(c *gin.Context) {
  852. c.JSON(http.StatusOK, gin.H{"version": version.Version})
  853. })
  854. }
  855. return r
  856. }
  857. func Serve(ln net.Listener) error {
  858. level := slog.LevelInfo
  859. if debug := os.Getenv("OLLAMA_DEBUG"); debug != "" {
  860. level = slog.LevelDebug
  861. }
  862. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  863. Level: level,
  864. AddSource: true,
  865. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  866. if attr.Key == slog.SourceKey {
  867. source := attr.Value.Any().(*slog.Source)
  868. source.File = filepath.Base(source.File)
  869. }
  870. return attr
  871. },
  872. })
  873. slog.SetDefault(slog.New(handler))
  874. blobsDir, err := GetBlobsPath("")
  875. if err != nil {
  876. return err
  877. }
  878. if err := fixBlobs(blobsDir); err != nil {
  879. return err
  880. }
  881. if noprune := os.Getenv("OLLAMA_NOPRUNE"); noprune == "" {
  882. // clean up unused layers and manifests
  883. if err := PruneLayers(); err != nil {
  884. return err
  885. }
  886. manifestsPath, err := GetManifestPath()
  887. if err != nil {
  888. return err
  889. }
  890. if err := PruneDirectory(manifestsPath); err != nil {
  891. return err
  892. }
  893. }
  894. ctx, done := context.WithCancel(context.Background())
  895. sched := InitScheduler(ctx)
  896. s := &Server{addr: ln.Addr(), sched: sched}
  897. r := s.GenerateRoutes()
  898. slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
  899. srvr := &http.Server{
  900. Handler: r,
  901. }
  902. // listen for a ctrl+c and stop any loaded llm
  903. signals := make(chan os.Signal, 1)
  904. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  905. go func() {
  906. <-signals
  907. done()
  908. sched.unloadAllRunners()
  909. gpu.Cleanup()
  910. os.Exit(0)
  911. }()
  912. if err := llm.Init(); err != nil {
  913. return fmt.Errorf("unable to initialize llm library %w", err)
  914. }
  915. s.sched.Run(ctx)
  916. // At startup we retrieve GPU information so we can get log messages before loading a model
  917. // This will log warnings to the log in case we have problems with detected GPUs
  918. _ = gpu.GetGPUInfo()
  919. return srvr.Serve(ln)
  920. }
  921. func waitForStream(c *gin.Context, ch chan interface{}) {
  922. c.Header("Content-Type", "application/json")
  923. for resp := range ch {
  924. switch r := resp.(type) {
  925. case api.ProgressResponse:
  926. if r.Status == "success" {
  927. c.JSON(http.StatusOK, r)
  928. return
  929. }
  930. case gin.H:
  931. if errorMsg, ok := r["error"].(string); ok {
  932. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  933. return
  934. } else {
  935. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  936. return
  937. }
  938. default:
  939. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  940. return
  941. }
  942. }
  943. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  944. }
  945. func streamResponse(c *gin.Context, ch chan any) {
  946. c.Header("Content-Type", "application/x-ndjson")
  947. c.Stream(func(w io.Writer) bool {
  948. val, ok := <-ch
  949. if !ok {
  950. return false
  951. }
  952. bts, err := json.Marshal(val)
  953. if err != nil {
  954. slog.Info(fmt.Sprintf("streamResponse: json.Marshal failed with %s", err))
  955. return false
  956. }
  957. // Delineate chunks with new-line delimiter
  958. bts = append(bts, '\n')
  959. if _, err := w.Write(bts); err != nil {
  960. slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
  961. return false
  962. }
  963. return true
  964. })
  965. }
  966. // ChatPrompt builds up a prompt from a series of messages for the currently `loaded` model
  967. func chatPrompt(ctx context.Context, runner *runnerRef, template string, messages []api.Message, numCtx int) (string, error) {
  968. encode := func(s string) ([]int, error) {
  969. return runner.llama.Tokenize(ctx, s)
  970. }
  971. prompt, err := ChatPrompt(template, messages, numCtx, encode)
  972. if err != nil {
  973. return "", err
  974. }
  975. return prompt, nil
  976. }
  977. func (s *Server) ChatHandler(c *gin.Context) {
  978. checkpointStart := time.Now()
  979. var req api.ChatRequest
  980. err := c.ShouldBindJSON(&req)
  981. switch {
  982. case errors.Is(err, io.EOF):
  983. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  984. return
  985. case err != nil:
  986. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  987. return
  988. }
  989. // validate the request
  990. switch {
  991. case req.Model == "":
  992. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  993. return
  994. case len(req.Format) > 0 && req.Format != "json":
  995. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
  996. return
  997. }
  998. model, err := GetModel(req.Model)
  999. if err != nil {
  1000. var pErr *fs.PathError
  1001. if errors.As(err, &pErr) {
  1002. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  1003. return
  1004. }
  1005. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  1006. return
  1007. }
  1008. if model.IsEmbedding() {
  1009. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "embedding models do not support chat"})
  1010. return
  1011. }
  1012. opts, err := modelOptions(model, req.Options)
  1013. if err != nil {
  1014. if errors.Is(err, api.ErrInvalidOpts) {
  1015. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  1016. return
  1017. }
  1018. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  1019. return
  1020. }
  1021. var sessionDuration time.Duration
  1022. if req.KeepAlive == nil {
  1023. sessionDuration = getDefaultSessionDuration()
  1024. } else {
  1025. sessionDuration = req.KeepAlive.Duration
  1026. }
  1027. rCh, eCh := s.sched.GetRunner(c.Request.Context(), model, opts, sessionDuration)
  1028. var runner *runnerRef
  1029. select {
  1030. case runner = <-rCh:
  1031. case err = <-eCh:
  1032. if errors.Is(err, context.Canceled) {
  1033. c.JSON(499, gin.H{"error": "request canceled"})
  1034. return
  1035. }
  1036. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  1037. return
  1038. }
  1039. checkpointLoaded := time.Now()
  1040. // if the first message is not a system message, then add the model's default system message
  1041. if len(req.Messages) > 0 && req.Messages[0].Role != "system" {
  1042. req.Messages = append([]api.Message{
  1043. {
  1044. Role: "system",
  1045. Content: model.System,
  1046. },
  1047. }, req.Messages...)
  1048. }
  1049. prompt, err := chatPrompt(c.Request.Context(), runner, model.Template, req.Messages, opts.NumCtx)
  1050. if err != nil {
  1051. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  1052. return
  1053. }
  1054. // an empty request loads the model
  1055. if len(req.Messages) == 0 || prompt == "" {
  1056. resp := api.ChatResponse{
  1057. CreatedAt: time.Now().UTC(),
  1058. Model: req.Model,
  1059. Done: true,
  1060. Message: api.Message{Role: "assistant"},
  1061. }
  1062. c.JSON(http.StatusOK, resp)
  1063. return
  1064. }
  1065. // only send images that are in the prompt
  1066. var i int
  1067. var images []llm.ImageData
  1068. for _, m := range req.Messages {
  1069. for _, img := range m.Images {
  1070. if !isSupportedImageType(img) {
  1071. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "unsupported image format"})
  1072. return
  1073. }
  1074. if strings.Contains(prompt, fmt.Sprintf("[img-%d]", i)) {
  1075. images = append(images, llm.ImageData{Data: img, ID: i})
  1076. }
  1077. i += 1
  1078. }
  1079. }
  1080. slog.Debug("chat handler", "prompt", prompt, "images", len(images))
  1081. ch := make(chan any)
  1082. go func() {
  1083. defer close(ch)
  1084. fn := func(r llm.CompletionResponse) {
  1085. resp := api.ChatResponse{
  1086. Model: req.Model,
  1087. CreatedAt: time.Now().UTC(),
  1088. Message: api.Message{Role: "assistant", Content: r.Content},
  1089. Done: r.Done,
  1090. Metrics: api.Metrics{
  1091. PromptEvalCount: r.PromptEvalCount,
  1092. PromptEvalDuration: r.PromptEvalDuration,
  1093. EvalCount: r.EvalCount,
  1094. EvalDuration: r.EvalDuration,
  1095. },
  1096. }
  1097. if r.Done {
  1098. resp.TotalDuration = time.Since(checkpointStart)
  1099. resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  1100. }
  1101. ch <- resp
  1102. }
  1103. if err := runner.llama.Completion(c.Request.Context(), llm.CompletionRequest{
  1104. Prompt: prompt,
  1105. Format: req.Format,
  1106. Images: images,
  1107. Options: opts,
  1108. }, fn); err != nil {
  1109. ch <- gin.H{"error": err.Error()}
  1110. }
  1111. }()
  1112. if req.Stream != nil && !*req.Stream {
  1113. // Accumulate responses into the final response
  1114. var final api.ChatResponse
  1115. var sb strings.Builder
  1116. for resp := range ch {
  1117. switch r := resp.(type) {
  1118. case api.ChatResponse:
  1119. sb.WriteString(r.Message.Content)
  1120. final = r
  1121. case gin.H:
  1122. if errorMsg, ok := r["error"].(string); ok {
  1123. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  1124. return
  1125. } else {
  1126. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in response"})
  1127. return
  1128. }
  1129. default:
  1130. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error"})
  1131. return
  1132. }
  1133. }
  1134. final.Message = api.Message{Role: "assistant", Content: sb.String()}
  1135. c.JSON(http.StatusOK, final)
  1136. return
  1137. }
  1138. streamResponse(c, ch)
  1139. }