routes.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  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), strings.ToUpper(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. c.Status(http.StatusCreated)
  732. }
  733. var defaultAllowOrigins = []string{
  734. "localhost",
  735. "127.0.0.1",
  736. "0.0.0.0",
  737. }
  738. func isLocalIP(ip netip.Addr) bool {
  739. if interfaces, err := net.Interfaces(); err == nil {
  740. for _, iface := range interfaces {
  741. addrs, err := iface.Addrs()
  742. if err != nil {
  743. continue
  744. }
  745. for _, a := range addrs {
  746. if parsed, _, err := net.ParseCIDR(a.String()); err == nil {
  747. if parsed.String() == ip.String() {
  748. return true
  749. }
  750. }
  751. }
  752. }
  753. }
  754. return false
  755. }
  756. func allowedHost(host string) bool {
  757. if host == "" || host == "localhost" {
  758. return true
  759. }
  760. if hostname, err := os.Hostname(); err == nil && host == hostname {
  761. return true
  762. }
  763. var tlds = []string{
  764. "localhost",
  765. "local",
  766. "internal",
  767. }
  768. // check if the host is a local TLD
  769. for _, tld := range tlds {
  770. if strings.HasSuffix(host, "."+tld) {
  771. return true
  772. }
  773. }
  774. return false
  775. }
  776. func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
  777. return func(c *gin.Context) {
  778. if addr == nil {
  779. c.Next()
  780. return
  781. }
  782. if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
  783. c.Next()
  784. return
  785. }
  786. host, _, err := net.SplitHostPort(c.Request.Host)
  787. if err != nil {
  788. host = c.Request.Host
  789. }
  790. if addr, err := netip.ParseAddr(host); err == nil {
  791. if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
  792. c.Next()
  793. return
  794. }
  795. }
  796. if allowedHost(host) {
  797. c.Next()
  798. return
  799. }
  800. c.AbortWithStatus(http.StatusForbidden)
  801. }
  802. }
  803. func (s *Server) GenerateRoutes() http.Handler {
  804. config := cors.DefaultConfig()
  805. config.AllowWildcard = true
  806. config.AllowBrowserExtensions = true
  807. if allowedOrigins := strings.Trim(os.Getenv("OLLAMA_ORIGINS"), "\"'"); allowedOrigins != "" {
  808. config.AllowOrigins = strings.Split(allowedOrigins, ",")
  809. }
  810. for _, allowOrigin := range defaultAllowOrigins {
  811. config.AllowOrigins = append(config.AllowOrigins,
  812. fmt.Sprintf("http://%s", allowOrigin),
  813. fmt.Sprintf("https://%s", allowOrigin),
  814. fmt.Sprintf("http://%s:*", allowOrigin),
  815. fmt.Sprintf("https://%s:*", allowOrigin),
  816. )
  817. }
  818. r := gin.Default()
  819. r.Use(
  820. cors.New(config),
  821. allowedHostsMiddleware(s.addr),
  822. )
  823. r.POST("/api/pull", s.PullModelHandler)
  824. r.POST("/api/generate", s.GenerateHandler)
  825. r.POST("/api/chat", s.ChatHandler)
  826. r.POST("/api/embeddings", s.EmbeddingsHandler)
  827. r.POST("/api/create", s.CreateModelHandler)
  828. r.POST("/api/push", s.PushModelHandler)
  829. r.POST("/api/copy", s.CopyModelHandler)
  830. r.DELETE("/api/delete", s.DeleteModelHandler)
  831. r.POST("/api/show", s.ShowModelHandler)
  832. r.POST("/api/blobs/:digest", s.CreateBlobHandler)
  833. r.HEAD("/api/blobs/:digest", s.HeadBlobHandler)
  834. // Compatibility endpoints
  835. r.POST("/v1/chat/completions", openai.Middleware(), s.ChatHandler)
  836. for _, method := range []string{http.MethodGet, http.MethodHead} {
  837. r.Handle(method, "/", func(c *gin.Context) {
  838. c.String(http.StatusOK, "Ollama is running")
  839. })
  840. r.Handle(method, "/api/tags", s.ListModelsHandler)
  841. r.Handle(method, "/api/version", func(c *gin.Context) {
  842. c.JSON(http.StatusOK, gin.H{"version": version.Version})
  843. })
  844. }
  845. return r
  846. }
  847. func Serve(ln net.Listener) error {
  848. level := slog.LevelInfo
  849. if debug := os.Getenv("OLLAMA_DEBUG"); debug != "" {
  850. level = slog.LevelDebug
  851. }
  852. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  853. Level: level,
  854. AddSource: true,
  855. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  856. if attr.Key == slog.SourceKey {
  857. source := attr.Value.Any().(*slog.Source)
  858. source.File = filepath.Base(source.File)
  859. }
  860. return attr
  861. },
  862. })
  863. slog.SetDefault(slog.New(handler))
  864. blobsDir, err := GetBlobsPath("")
  865. if err != nil {
  866. return err
  867. }
  868. if err := fixBlobs(blobsDir); err != nil {
  869. return err
  870. }
  871. if noprune := os.Getenv("OLLAMA_NOPRUNE"); noprune == "" {
  872. // clean up unused layers and manifests
  873. if err := PruneLayers(); err != nil {
  874. return err
  875. }
  876. manifestsPath, err := GetManifestPath()
  877. if err != nil {
  878. return err
  879. }
  880. if err := PruneDirectory(manifestsPath); err != nil {
  881. return err
  882. }
  883. }
  884. ctx, done := context.WithCancel(context.Background())
  885. sched := InitScheduler(ctx)
  886. s := &Server{addr: ln.Addr(), sched: sched}
  887. r := s.GenerateRoutes()
  888. slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
  889. srvr := &http.Server{
  890. Handler: r,
  891. }
  892. // listen for a ctrl+c and stop any loaded llm
  893. signals := make(chan os.Signal, 1)
  894. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  895. go func() {
  896. <-signals
  897. done()
  898. sched.unloadAllRunners()
  899. gpu.Cleanup()
  900. os.Exit(0)
  901. }()
  902. if err := llm.Init(); err != nil {
  903. return fmt.Errorf("unable to initialize llm library %w", err)
  904. }
  905. s.sched.Run(ctx)
  906. // At startup we retrieve GPU information so we can get log messages before loading a model
  907. // This will log warnings to the log in case we have problems with detected GPUs
  908. _ = gpu.GetGPUInfo()
  909. return srvr.Serve(ln)
  910. }
  911. func waitForStream(c *gin.Context, ch chan interface{}) {
  912. c.Header("Content-Type", "application/json")
  913. for resp := range ch {
  914. switch r := resp.(type) {
  915. case api.ProgressResponse:
  916. if r.Status == "success" {
  917. c.JSON(http.StatusOK, r)
  918. return
  919. }
  920. case gin.H:
  921. if errorMsg, ok := r["error"].(string); ok {
  922. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  923. return
  924. } else {
  925. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  926. return
  927. }
  928. default:
  929. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  930. return
  931. }
  932. }
  933. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  934. }
  935. func streamResponse(c *gin.Context, ch chan any) {
  936. c.Header("Content-Type", "application/x-ndjson")
  937. c.Stream(func(w io.Writer) bool {
  938. val, ok := <-ch
  939. if !ok {
  940. return false
  941. }
  942. bts, err := json.Marshal(val)
  943. if err != nil {
  944. slog.Info(fmt.Sprintf("streamResponse: json.Marshal failed with %s", err))
  945. return false
  946. }
  947. // Delineate chunks with new-line delimiter
  948. bts = append(bts, '\n')
  949. if _, err := w.Write(bts); err != nil {
  950. slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
  951. return false
  952. }
  953. return true
  954. })
  955. }
  956. // ChatPrompt builds up a prompt from a series of messages for the currently `loaded` model
  957. func chatPrompt(ctx context.Context, runner *runnerRef, template string, messages []api.Message, numCtx int) (string, error) {
  958. encode := func(s string) ([]int, error) {
  959. return runner.llama.Tokenize(ctx, s)
  960. }
  961. prompt, err := ChatPrompt(template, messages, numCtx, encode)
  962. if err != nil {
  963. return "", err
  964. }
  965. return prompt, nil
  966. }
  967. func (s *Server) ChatHandler(c *gin.Context) {
  968. checkpointStart := time.Now()
  969. var req api.ChatRequest
  970. err := c.ShouldBindJSON(&req)
  971. switch {
  972. case errors.Is(err, io.EOF):
  973. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  974. return
  975. case err != nil:
  976. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  977. return
  978. }
  979. // validate the request
  980. switch {
  981. case req.Model == "":
  982. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  983. return
  984. case len(req.Format) > 0 && req.Format != "json":
  985. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
  986. return
  987. }
  988. model, err := GetModel(req.Model)
  989. if err != nil {
  990. var pErr *fs.PathError
  991. if errors.As(err, &pErr) {
  992. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  993. return
  994. }
  995. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  996. return
  997. }
  998. if model.IsEmbedding() {
  999. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "embedding models do not support chat"})
  1000. return
  1001. }
  1002. opts, err := modelOptions(model, req.Options)
  1003. if err != nil {
  1004. if errors.Is(err, api.ErrInvalidOpts) {
  1005. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  1006. return
  1007. }
  1008. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  1009. return
  1010. }
  1011. var sessionDuration time.Duration
  1012. if req.KeepAlive == nil {
  1013. sessionDuration = getDefaultSessionDuration()
  1014. } else {
  1015. sessionDuration = req.KeepAlive.Duration
  1016. }
  1017. rCh, eCh := s.sched.GetRunner(c.Request.Context(), model, opts, sessionDuration)
  1018. var runner *runnerRef
  1019. select {
  1020. case runner = <-rCh:
  1021. case err = <-eCh:
  1022. if errors.Is(err, context.Canceled) {
  1023. c.JSON(499, gin.H{"error": "request canceled"})
  1024. return
  1025. }
  1026. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  1027. return
  1028. }
  1029. checkpointLoaded := time.Now()
  1030. // if the first message is not a system message, then add the model's default system message
  1031. if len(req.Messages) > 0 && req.Messages[0].Role != "system" {
  1032. req.Messages = append([]api.Message{
  1033. {
  1034. Role: "system",
  1035. Content: model.System,
  1036. },
  1037. }, req.Messages...)
  1038. }
  1039. prompt, err := chatPrompt(c.Request.Context(), runner, model.Template, req.Messages, opts.NumCtx)
  1040. if err != nil {
  1041. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  1042. return
  1043. }
  1044. // an empty request loads the model
  1045. if len(req.Messages) == 0 || prompt == "" {
  1046. resp := api.ChatResponse{
  1047. CreatedAt: time.Now().UTC(),
  1048. Model: req.Model,
  1049. Done: true,
  1050. Message: api.Message{Role: "assistant"},
  1051. }
  1052. c.JSON(http.StatusOK, resp)
  1053. return
  1054. }
  1055. // only send images that are in the prompt
  1056. var i int
  1057. var images []llm.ImageData
  1058. for _, m := range req.Messages {
  1059. for _, img := range m.Images {
  1060. if !isSupportedImageType(img) {
  1061. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "unsupported image format"})
  1062. return
  1063. }
  1064. if strings.Contains(prompt, fmt.Sprintf("[img-%d]", i)) {
  1065. images = append(images, llm.ImageData{Data: img, ID: i})
  1066. }
  1067. i += 1
  1068. }
  1069. }
  1070. slog.Debug("chat handler", "prompt", prompt, "images", len(images))
  1071. ch := make(chan any)
  1072. go func() {
  1073. defer close(ch)
  1074. fn := func(r llm.CompletionResponse) {
  1075. resp := api.ChatResponse{
  1076. Model: req.Model,
  1077. CreatedAt: time.Now().UTC(),
  1078. Message: api.Message{Role: "assistant", Content: r.Content},
  1079. Done: r.Done,
  1080. Metrics: api.Metrics{
  1081. PromptEvalCount: r.PromptEvalCount,
  1082. PromptEvalDuration: r.PromptEvalDuration,
  1083. EvalCount: r.EvalCount,
  1084. EvalDuration: r.EvalDuration,
  1085. },
  1086. }
  1087. if r.Done {
  1088. resp.TotalDuration = time.Since(checkpointStart)
  1089. resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  1090. }
  1091. ch <- resp
  1092. }
  1093. if err := runner.llama.Completion(c.Request.Context(), llm.CompletionRequest{
  1094. Prompt: prompt,
  1095. Format: req.Format,
  1096. Images: images,
  1097. Options: opts,
  1098. }, fn); err != nil {
  1099. ch <- gin.H{"error": err.Error()}
  1100. }
  1101. }()
  1102. if req.Stream != nil && !*req.Stream {
  1103. // Accumulate responses into the final response
  1104. var final api.ChatResponse
  1105. var sb strings.Builder
  1106. for resp := range ch {
  1107. switch r := resp.(type) {
  1108. case api.ChatResponse:
  1109. sb.WriteString(r.Message.Content)
  1110. final = r
  1111. case gin.H:
  1112. if errorMsg, ok := r["error"].(string); ok {
  1113. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  1114. return
  1115. } else {
  1116. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in response"})
  1117. return
  1118. }
  1119. default:
  1120. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error"})
  1121. return
  1122. }
  1123. }
  1124. final.Message = api.Message{Role: "assistant", Content: sb.String()}
  1125. c.JSON(http.StatusOK, final)
  1126. return
  1127. }
  1128. streamResponse(c, ch)
  1129. }