routes.go 33 KB

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