routes.go 33 KB

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