routes.go 32 KB

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