routes.go 33 KB

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