routes.go 33 KB

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