routes.go 33 KB

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