routes.go 32 KB

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