routes.go 32 KB

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