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