routes.go 33 KB

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