routes.go 31 KB

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