routes.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  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. sessionDuration := defaultSessionDuration
  156. if err := load(c, model, opts, sessionDuration); err != nil {
  157. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  158. return
  159. }
  160. // an empty request loads the model
  161. if req.Prompt == "" && req.Template == "" && req.System == "" {
  162. c.JSON(http.StatusOK, api.GenerateResponse{
  163. CreatedAt: time.Now().UTC(),
  164. Model: req.Model,
  165. Done: true,
  166. })
  167. return
  168. }
  169. checkpointLoaded := time.Now()
  170. var prompt string
  171. var promptVars PromptVars
  172. switch {
  173. case req.Raw:
  174. prompt = req.Prompt
  175. case req.Prompt != "":
  176. if req.Template != "" {
  177. // override the default model template
  178. model.Template = req.Template
  179. }
  180. var rebuild strings.Builder
  181. if req.Context != nil {
  182. // TODO: context is deprecated, at some point the context logic within this conditional should be removed
  183. prevCtx, err := loaded.runner.Decode(c.Request.Context(), req.Context)
  184. if err != nil {
  185. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  186. return
  187. }
  188. // Remove leading spaces from prevCtx if present
  189. prevCtx = strings.TrimPrefix(prevCtx, " ")
  190. rebuild.WriteString(prevCtx)
  191. }
  192. promptVars = PromptVars{
  193. System: req.System,
  194. Prompt: req.Prompt,
  195. First: len(req.Context) == 0,
  196. }
  197. p, err := model.PreResponsePrompt(promptVars)
  198. if err != nil {
  199. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  200. return
  201. }
  202. rebuild.WriteString(p)
  203. prompt = rebuild.String()
  204. }
  205. ch := make(chan any)
  206. var generated strings.Builder
  207. go func() {
  208. defer close(ch)
  209. fn := func(r llm.PredictResult) {
  210. // Update model expiration
  211. loaded.expireAt = time.Now().Add(sessionDuration)
  212. loaded.expireTimer.Reset(sessionDuration)
  213. // Build up the full response
  214. if _, err := generated.WriteString(r.Content); err != nil {
  215. ch <- gin.H{"error": err.Error()}
  216. return
  217. }
  218. resp := api.GenerateResponse{
  219. Model: req.Model,
  220. CreatedAt: time.Now().UTC(),
  221. Done: r.Done,
  222. Response: r.Content,
  223. Metrics: api.Metrics{
  224. PromptEvalCount: r.PromptEvalCount,
  225. PromptEvalDuration: r.PromptEvalDuration,
  226. EvalCount: r.EvalCount,
  227. EvalDuration: r.EvalDuration,
  228. },
  229. }
  230. if r.Done {
  231. resp.TotalDuration = time.Since(checkpointStart)
  232. resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  233. if !req.Raw {
  234. // append the generated text to the history and template it if needed
  235. promptVars.Response = generated.String()
  236. result, err := model.PostResponseTemplate(promptVars)
  237. if err != nil {
  238. ch <- gin.H{"error": err.Error()}
  239. return
  240. }
  241. embd, err := loaded.runner.Encode(c.Request.Context(), prompt+result)
  242. if err != nil {
  243. ch <- gin.H{"error": err.Error()}
  244. return
  245. }
  246. resp.Context = embd
  247. }
  248. }
  249. ch <- resp
  250. }
  251. // Start prediction
  252. predictReq := llm.PredictOpts{
  253. Prompt: prompt,
  254. Format: req.Format,
  255. Images: req.Images,
  256. Options: opts,
  257. }
  258. if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
  259. ch <- gin.H{"error": err.Error()}
  260. }
  261. }()
  262. if req.Stream != nil && !*req.Stream {
  263. // Accumulate responses into the final response
  264. var final api.GenerateResponse
  265. var sb strings.Builder
  266. for resp := range ch {
  267. switch r := resp.(type) {
  268. case api.GenerateResponse:
  269. sb.WriteString(r.Response)
  270. final = r
  271. case gin.H:
  272. if errorMsg, ok := r["error"].(string); ok {
  273. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  274. return
  275. } else {
  276. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in response"})
  277. return
  278. }
  279. default:
  280. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error"})
  281. return
  282. }
  283. }
  284. final.Response = sb.String()
  285. c.JSON(http.StatusOK, final)
  286. return
  287. }
  288. streamResponse(c, ch)
  289. }
  290. func EmbeddingHandler(c *gin.Context) {
  291. loaded.mu.Lock()
  292. defer loaded.mu.Unlock()
  293. var req api.EmbeddingRequest
  294. err := c.ShouldBindJSON(&req)
  295. switch {
  296. case errors.Is(err, io.EOF):
  297. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  298. return
  299. case err != nil:
  300. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  301. return
  302. }
  303. if req.Model == "" {
  304. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  305. return
  306. }
  307. model, err := GetModel(req.Model)
  308. if err != nil {
  309. var pErr *fs.PathError
  310. if errors.As(err, &pErr) {
  311. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  312. return
  313. }
  314. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  315. return
  316. }
  317. opts, err := modelOptions(model, req.Options)
  318. if err != nil {
  319. if errors.Is(err, api.ErrInvalidOpts) {
  320. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  321. return
  322. }
  323. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  324. return
  325. }
  326. sessionDuration := defaultSessionDuration
  327. if err := load(c, model, opts, sessionDuration); err != nil {
  328. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  329. return
  330. }
  331. if !loaded.Options.EmbeddingOnly {
  332. c.JSON(http.StatusBadRequest, gin.H{"error": "embedding option must be set to true"})
  333. return
  334. }
  335. embedding, err := loaded.runner.Embedding(c.Request.Context(), req.Prompt)
  336. if err != nil {
  337. slog.Info(fmt.Sprintf("embedding generation failed: %v", err))
  338. c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
  339. return
  340. }
  341. resp := api.EmbeddingResponse{
  342. Embedding: embedding,
  343. }
  344. c.JSON(http.StatusOK, resp)
  345. }
  346. func PullModelHandler(c *gin.Context) {
  347. var req api.PullRequest
  348. err := c.ShouldBindJSON(&req)
  349. switch {
  350. case errors.Is(err, io.EOF):
  351. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  352. return
  353. case err != nil:
  354. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  355. return
  356. }
  357. var model string
  358. if req.Model != "" {
  359. model = req.Model
  360. } else if req.Name != "" {
  361. model = req.Name
  362. } else {
  363. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  364. return
  365. }
  366. ch := make(chan any)
  367. go func() {
  368. defer close(ch)
  369. fn := func(r api.ProgressResponse) {
  370. ch <- r
  371. }
  372. regOpts := &RegistryOptions{
  373. Insecure: req.Insecure,
  374. }
  375. ctx, cancel := context.WithCancel(c.Request.Context())
  376. defer cancel()
  377. if err := PullModel(ctx, model, regOpts, fn); err != nil {
  378. ch <- gin.H{"error": err.Error()}
  379. }
  380. }()
  381. if req.Stream != nil && !*req.Stream {
  382. waitForStream(c, ch)
  383. return
  384. }
  385. streamResponse(c, ch)
  386. }
  387. func PushModelHandler(c *gin.Context) {
  388. var req api.PushRequest
  389. err := c.ShouldBindJSON(&req)
  390. switch {
  391. case errors.Is(err, io.EOF):
  392. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  393. return
  394. case err != nil:
  395. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  396. return
  397. }
  398. var model string
  399. if req.Model != "" {
  400. model = req.Model
  401. } else if req.Name != "" {
  402. model = req.Name
  403. } else {
  404. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  405. return
  406. }
  407. ch := make(chan any)
  408. go func() {
  409. defer close(ch)
  410. fn := func(r api.ProgressResponse) {
  411. ch <- r
  412. }
  413. regOpts := &RegistryOptions{
  414. Insecure: req.Insecure,
  415. }
  416. ctx, cancel := context.WithCancel(c.Request.Context())
  417. defer cancel()
  418. if err := PushModel(ctx, model, regOpts, fn); err != nil {
  419. ch <- gin.H{"error": err.Error()}
  420. }
  421. }()
  422. if req.Stream != nil && !*req.Stream {
  423. waitForStream(c, ch)
  424. return
  425. }
  426. streamResponse(c, ch)
  427. }
  428. func CreateModelHandler(c *gin.Context) {
  429. var req api.CreateRequest
  430. err := c.ShouldBindJSON(&req)
  431. switch {
  432. case errors.Is(err, io.EOF):
  433. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  434. return
  435. case err != nil:
  436. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  437. return
  438. }
  439. var model string
  440. if req.Model != "" {
  441. model = req.Model
  442. } else if req.Name != "" {
  443. model = req.Name
  444. } else {
  445. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  446. return
  447. }
  448. if err := ParseModelPath(model).Validate(); err != nil {
  449. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  450. return
  451. }
  452. if req.Path == "" && req.Modelfile == "" {
  453. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
  454. return
  455. }
  456. var modelfile io.Reader = strings.NewReader(req.Modelfile)
  457. if req.Path != "" && req.Modelfile == "" {
  458. mf, err := os.Open(req.Path)
  459. if err != nil {
  460. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
  461. return
  462. }
  463. defer mf.Close()
  464. modelfile = mf
  465. }
  466. commands, err := parser.Parse(modelfile)
  467. if err != nil {
  468. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  469. return
  470. }
  471. ch := make(chan any)
  472. go func() {
  473. defer close(ch)
  474. fn := func(resp api.ProgressResponse) {
  475. ch <- resp
  476. }
  477. ctx, cancel := context.WithCancel(c.Request.Context())
  478. defer cancel()
  479. if err := CreateModel(ctx, model, filepath.Dir(req.Path), commands, fn); err != nil {
  480. ch <- gin.H{"error": err.Error()}
  481. }
  482. }()
  483. if req.Stream != nil && !*req.Stream {
  484. waitForStream(c, ch)
  485. return
  486. }
  487. streamResponse(c, ch)
  488. }
  489. func DeleteModelHandler(c *gin.Context) {
  490. var req api.DeleteRequest
  491. err := c.ShouldBindJSON(&req)
  492. switch {
  493. case errors.Is(err, io.EOF):
  494. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  495. return
  496. case err != nil:
  497. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  498. return
  499. }
  500. var model string
  501. if req.Model != "" {
  502. model = req.Model
  503. } else if req.Name != "" {
  504. model = req.Name
  505. } else {
  506. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  507. return
  508. }
  509. if err := DeleteModel(model); err != nil {
  510. if os.IsNotExist(err) {
  511. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", model)})
  512. } else {
  513. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  514. }
  515. return
  516. }
  517. manifestsPath, err := GetManifestPath()
  518. if err != nil {
  519. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  520. return
  521. }
  522. if err := PruneDirectory(manifestsPath); err != nil {
  523. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  524. return
  525. }
  526. c.JSON(http.StatusOK, nil)
  527. }
  528. func ShowModelHandler(c *gin.Context) {
  529. var req api.ShowRequest
  530. err := c.ShouldBindJSON(&req)
  531. switch {
  532. case errors.Is(err, io.EOF):
  533. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  534. return
  535. case err != nil:
  536. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  537. return
  538. }
  539. if req.Model != "" {
  540. // noop
  541. } else if req.Name != "" {
  542. req.Model = req.Name
  543. } else {
  544. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  545. return
  546. }
  547. resp, err := GetModelInfo(req)
  548. if err != nil {
  549. if os.IsNotExist(err) {
  550. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
  551. } else {
  552. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  553. }
  554. return
  555. }
  556. c.JSON(http.StatusOK, resp)
  557. }
  558. func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
  559. model, err := GetModel(req.Model)
  560. if err != nil {
  561. return nil, err
  562. }
  563. modelDetails := api.ModelDetails{
  564. ParentModel: model.ParentModel,
  565. Format: model.Config.ModelFormat,
  566. Family: model.Config.ModelFamily,
  567. Families: model.Config.ModelFamilies,
  568. ParameterSize: model.Config.ModelType,
  569. QuantizationLevel: model.Config.FileType,
  570. }
  571. if req.System != "" {
  572. model.System = req.System
  573. }
  574. if req.Template != "" {
  575. model.Template = req.Template
  576. }
  577. msgs := make([]api.Message, 0)
  578. for _, msg := range model.Messages {
  579. msgs = append(msgs, api.Message{Role: msg.Role, Content: msg.Content})
  580. }
  581. resp := &api.ShowResponse{
  582. License: strings.Join(model.License, "\n"),
  583. System: model.System,
  584. Template: model.Template,
  585. Details: modelDetails,
  586. Messages: msgs,
  587. }
  588. var params []string
  589. cs := 30
  590. for k, v := range model.Options {
  591. switch val := v.(type) {
  592. case []interface{}:
  593. for _, nv := range val {
  594. params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
  595. }
  596. default:
  597. params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
  598. }
  599. }
  600. resp.Parameters = strings.Join(params, "\n")
  601. for k, v := range req.Options {
  602. if _, ok := req.Options[k]; ok {
  603. model.Options[k] = v
  604. }
  605. }
  606. mf, err := ShowModelfile(model)
  607. if err != nil {
  608. return nil, err
  609. }
  610. resp.Modelfile = mf
  611. return resp, nil
  612. }
  613. func ListModelsHandler(c *gin.Context) {
  614. models := make([]api.ModelResponse, 0)
  615. manifestsPath, err := GetManifestPath()
  616. if err != nil {
  617. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  618. return
  619. }
  620. modelResponse := func(modelName string) (api.ModelResponse, error) {
  621. model, err := GetModel(modelName)
  622. if err != nil {
  623. return api.ModelResponse{}, err
  624. }
  625. modelDetails := api.ModelDetails{
  626. Format: model.Config.ModelFormat,
  627. Family: model.Config.ModelFamily,
  628. Families: model.Config.ModelFamilies,
  629. ParameterSize: model.Config.ModelType,
  630. QuantizationLevel: model.Config.FileType,
  631. }
  632. return api.ModelResponse{
  633. Model: model.ShortName,
  634. Name: model.ShortName,
  635. Size: model.Size,
  636. Digest: model.Digest,
  637. Details: modelDetails,
  638. }, nil
  639. }
  640. walkFunc := func(path string, info os.FileInfo, _ error) error {
  641. if !info.IsDir() {
  642. path, tag := filepath.Split(path)
  643. model := strings.Trim(strings.TrimPrefix(path, manifestsPath), string(os.PathSeparator))
  644. modelPath := strings.Join([]string{model, tag}, ":")
  645. canonicalModelPath := strings.ReplaceAll(modelPath, string(os.PathSeparator), "/")
  646. resp, err := modelResponse(canonicalModelPath)
  647. if err != nil {
  648. slog.Info(fmt.Sprintf("skipping file: %s", canonicalModelPath))
  649. // nolint: nilerr
  650. return nil
  651. }
  652. resp.ModifiedAt = info.ModTime()
  653. models = append(models, resp)
  654. }
  655. return nil
  656. }
  657. if err := filepath.Walk(manifestsPath, walkFunc); err != nil {
  658. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  659. return
  660. }
  661. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  662. }
  663. func CopyModelHandler(c *gin.Context) {
  664. var req api.CopyRequest
  665. err := c.ShouldBindJSON(&req)
  666. switch {
  667. case errors.Is(err, io.EOF):
  668. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  669. return
  670. case err != nil:
  671. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  672. return
  673. }
  674. if req.Source == "" || req.Destination == "" {
  675. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
  676. return
  677. }
  678. if err := ParseModelPath(req.Destination).Validate(); err != nil {
  679. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  680. return
  681. }
  682. if err := CopyModel(req.Source, req.Destination); err != nil {
  683. if os.IsNotExist(err) {
  684. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  685. } else {
  686. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  687. }
  688. return
  689. }
  690. }
  691. func HeadBlobHandler(c *gin.Context) {
  692. path, err := GetBlobsPath(c.Param("digest"))
  693. if err != nil {
  694. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  695. return
  696. }
  697. if _, err := os.Stat(path); err != nil {
  698. c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("blob %q not found", c.Param("digest"))})
  699. return
  700. }
  701. c.Status(http.StatusOK)
  702. }
  703. func CreateBlobHandler(c *gin.Context) {
  704. layer, err := NewLayer(c.Request.Body, "")
  705. if err != nil {
  706. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  707. return
  708. }
  709. if layer.Digest != c.Param("digest") {
  710. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("digest mismatch, expected %q, got %q", c.Param("digest"), layer.Digest)})
  711. return
  712. }
  713. if _, err := layer.Commit(); err != nil {
  714. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  715. return
  716. }
  717. c.Status(http.StatusCreated)
  718. }
  719. var defaultAllowOrigins = []string{
  720. "localhost",
  721. "127.0.0.1",
  722. "0.0.0.0",
  723. }
  724. func NewServer() (*Server, error) {
  725. workDir, err := os.MkdirTemp("", "ollama")
  726. if err != nil {
  727. return nil, err
  728. }
  729. return &Server{
  730. WorkDir: workDir,
  731. }, nil
  732. }
  733. func (s *Server) GenerateRoutes() http.Handler {
  734. var origins []string
  735. if o := os.Getenv("OLLAMA_ORIGINS"); o != "" {
  736. origins = strings.Split(o, ",")
  737. }
  738. config := cors.DefaultConfig()
  739. config.AllowWildcard = true
  740. config.AllowBrowserExtensions = true
  741. config.AllowOrigins = origins
  742. for _, allowOrigin := range defaultAllowOrigins {
  743. config.AllowOrigins = append(config.AllowOrigins,
  744. fmt.Sprintf("http://%s", allowOrigin),
  745. fmt.Sprintf("https://%s", allowOrigin),
  746. fmt.Sprintf("http://%s:*", allowOrigin),
  747. fmt.Sprintf("https://%s:*", allowOrigin),
  748. )
  749. }
  750. r := gin.Default()
  751. r.Use(
  752. cors.New(config),
  753. func(c *gin.Context) {
  754. c.Set("workDir", s.WorkDir)
  755. c.Next()
  756. },
  757. )
  758. r.POST("/api/pull", PullModelHandler)
  759. r.POST("/api/generate", GenerateHandler)
  760. r.POST("/api/chat", ChatHandler)
  761. r.POST("/api/embeddings", EmbeddingHandler)
  762. r.POST("/api/create", CreateModelHandler)
  763. r.POST("/api/push", PushModelHandler)
  764. r.POST("/api/copy", CopyModelHandler)
  765. r.DELETE("/api/delete", DeleteModelHandler)
  766. r.POST("/api/show", ShowModelHandler)
  767. r.POST("/api/blobs/:digest", CreateBlobHandler)
  768. r.HEAD("/api/blobs/:digest", HeadBlobHandler)
  769. for _, method := range []string{http.MethodGet, http.MethodHead} {
  770. r.Handle(method, "/", func(c *gin.Context) {
  771. c.String(http.StatusOK, "Ollama is running")
  772. })
  773. r.Handle(method, "/api/tags", ListModelsHandler)
  774. r.Handle(method, "/api/version", func(c *gin.Context) {
  775. c.JSON(http.StatusOK, gin.H{"version": version.Version})
  776. })
  777. }
  778. return r
  779. }
  780. func Serve(ln net.Listener) error {
  781. if debug := os.Getenv("OLLAMA_DEBUG"); debug != "" {
  782. var programLevel = new(slog.LevelVar)
  783. h := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: programLevel, AddSource: true})
  784. slog.SetDefault(slog.New(h))
  785. programLevel.Set(slog.LevelDebug)
  786. slog.Debug("Debug logging enabled")
  787. }
  788. if noprune := os.Getenv("OLLAMA_NOPRUNE"); noprune == "" {
  789. // clean up unused layers and manifests
  790. if err := PruneLayers(); err != nil {
  791. return err
  792. }
  793. manifestsPath, err := GetManifestPath()
  794. if err != nil {
  795. return err
  796. }
  797. if err := PruneDirectory(manifestsPath); err != nil {
  798. return err
  799. }
  800. }
  801. s, err := NewServer()
  802. if err != nil {
  803. return err
  804. }
  805. r := s.GenerateRoutes()
  806. slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
  807. srvr := &http.Server{
  808. Handler: r,
  809. }
  810. // listen for a ctrl+c and stop any loaded llm
  811. signals := make(chan os.Signal, 1)
  812. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  813. go func() {
  814. <-signals
  815. if loaded.runner != nil {
  816. loaded.runner.Close()
  817. }
  818. os.RemoveAll(s.WorkDir)
  819. os.Exit(0)
  820. }()
  821. if err := llm.Init(s.WorkDir); err != nil {
  822. return fmt.Errorf("unable to initialize llm library %w", err)
  823. }
  824. if runtime.GOOS == "linux" { // TODO - windows too
  825. // check compatibility to log warnings
  826. if _, err := gpu.CheckVRAM(); err != nil {
  827. slog.Info(err.Error())
  828. }
  829. }
  830. return srvr.Serve(ln)
  831. }
  832. func waitForStream(c *gin.Context, ch chan interface{}) {
  833. c.Header("Content-Type", "application/json")
  834. for resp := range ch {
  835. switch r := resp.(type) {
  836. case api.ProgressResponse:
  837. if r.Status == "success" {
  838. c.JSON(http.StatusOK, r)
  839. return
  840. }
  841. case gin.H:
  842. if errorMsg, ok := r["error"].(string); ok {
  843. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  844. return
  845. } else {
  846. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  847. return
  848. }
  849. default:
  850. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  851. return
  852. }
  853. }
  854. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  855. }
  856. func streamResponse(c *gin.Context, ch chan any) {
  857. c.Header("Content-Type", "application/x-ndjson")
  858. c.Stream(func(w io.Writer) bool {
  859. val, ok := <-ch
  860. if !ok {
  861. return false
  862. }
  863. bts, err := json.Marshal(val)
  864. if err != nil {
  865. slog.Info(fmt.Sprintf("streamResponse: json.Marshal failed with %s", err))
  866. return false
  867. }
  868. // Delineate chunks with new-line delimiter
  869. bts = append(bts, '\n')
  870. if _, err := w.Write(bts); err != nil {
  871. slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
  872. return false
  873. }
  874. return true
  875. })
  876. }
  877. func ChatHandler(c *gin.Context) {
  878. loaded.mu.Lock()
  879. defer loaded.mu.Unlock()
  880. checkpointStart := time.Now()
  881. var req api.ChatRequest
  882. err := c.ShouldBindJSON(&req)
  883. switch {
  884. case errors.Is(err, io.EOF):
  885. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  886. return
  887. case err != nil:
  888. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  889. return
  890. }
  891. // validate the request
  892. switch {
  893. case req.Model == "":
  894. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  895. return
  896. case len(req.Format) > 0 && req.Format != "json":
  897. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
  898. return
  899. }
  900. model, err := GetModel(req.Model)
  901. if err != nil {
  902. var pErr *fs.PathError
  903. if errors.As(err, &pErr) {
  904. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  905. return
  906. }
  907. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  908. return
  909. }
  910. opts, err := modelOptions(model, req.Options)
  911. if err != nil {
  912. if errors.Is(err, api.ErrInvalidOpts) {
  913. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  914. return
  915. }
  916. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  917. return
  918. }
  919. sessionDuration := defaultSessionDuration
  920. if err := load(c, model, opts, sessionDuration); err != nil {
  921. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  922. return
  923. }
  924. // an empty request loads the model
  925. if len(req.Messages) == 0 {
  926. resp := api.ChatResponse{
  927. CreatedAt: time.Now().UTC(),
  928. Model: req.Model,
  929. Done: true,
  930. Message: api.Message{Role: "assistant"},
  931. }
  932. c.JSON(http.StatusOK, resp)
  933. return
  934. }
  935. checkpointLoaded := time.Now()
  936. prompt, images, err := model.ChatPrompt(req.Messages)
  937. if err != nil {
  938. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  939. return
  940. }
  941. ch := make(chan any)
  942. go func() {
  943. defer close(ch)
  944. fn := func(r llm.PredictResult) {
  945. // Update model expiration
  946. loaded.expireAt = time.Now().Add(sessionDuration)
  947. loaded.expireTimer.Reset(sessionDuration)
  948. resp := api.ChatResponse{
  949. Model: req.Model,
  950. CreatedAt: time.Now().UTC(),
  951. Message: api.Message{Role: "assistant", Content: r.Content},
  952. Done: r.Done,
  953. Metrics: api.Metrics{
  954. PromptEvalCount: r.PromptEvalCount,
  955. PromptEvalDuration: r.PromptEvalDuration,
  956. EvalCount: r.EvalCount,
  957. EvalDuration: r.EvalDuration,
  958. },
  959. }
  960. if r.Done {
  961. resp.TotalDuration = time.Since(checkpointStart)
  962. resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  963. }
  964. ch <- resp
  965. }
  966. // Start prediction
  967. predictReq := llm.PredictOpts{
  968. Prompt: prompt,
  969. Format: req.Format,
  970. Images: images,
  971. Options: opts,
  972. }
  973. if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
  974. ch <- gin.H{"error": err.Error()}
  975. }
  976. }()
  977. if req.Stream != nil && !*req.Stream {
  978. // Accumulate responses into the final response
  979. var final api.ChatResponse
  980. var sb strings.Builder
  981. for resp := range ch {
  982. switch r := resp.(type) {
  983. case api.ChatResponse:
  984. sb.WriteString(r.Message.Content)
  985. final = r
  986. case gin.H:
  987. if errorMsg, ok := r["error"].(string); ok {
  988. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  989. return
  990. } else {
  991. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in response"})
  992. return
  993. }
  994. default:
  995. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error"})
  996. return
  997. }
  998. }
  999. final.Message = api.Message{Role: "assistant", Content: sb.String()}
  1000. c.JSON(http.StatusOK, final)
  1001. return
  1002. }
  1003. streamResponse(c, ch)
  1004. }