routes.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  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(fmt.Sprintf("prompt: %s", 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. if debug := os.Getenv("OLLAMA_DEBUG"); debug != "" {
  796. var programLevel = new(slog.LevelVar)
  797. h := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: programLevel, AddSource: true})
  798. slog.SetDefault(slog.New(h))
  799. programLevel.Set(slog.LevelDebug)
  800. slog.Debug("Debug logging enabled")
  801. }
  802. if noprune := os.Getenv("OLLAMA_NOPRUNE"); noprune == "" {
  803. // clean up unused layers and manifests
  804. if err := PruneLayers(); err != nil {
  805. return err
  806. }
  807. manifestsPath, err := GetManifestPath()
  808. if err != nil {
  809. return err
  810. }
  811. if err := PruneDirectory(manifestsPath); err != nil {
  812. return err
  813. }
  814. }
  815. s, err := NewServer()
  816. if err != nil {
  817. return err
  818. }
  819. r := s.GenerateRoutes()
  820. slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
  821. srvr := &http.Server{
  822. Handler: r,
  823. }
  824. // listen for a ctrl+c and stop any loaded llm
  825. signals := make(chan os.Signal, 1)
  826. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  827. go func() {
  828. <-signals
  829. if loaded.runner != nil {
  830. loaded.runner.Close()
  831. }
  832. os.RemoveAll(s.WorkDir)
  833. os.Exit(0)
  834. }()
  835. if err := llm.Init(s.WorkDir); err != nil {
  836. return fmt.Errorf("unable to initialize llm library %w", err)
  837. }
  838. if runtime.GOOS == "linux" { // TODO - windows too
  839. // check compatibility to log warnings
  840. if _, err := gpu.CheckVRAM(); err != nil {
  841. slog.Info(err.Error())
  842. }
  843. }
  844. return srvr.Serve(ln)
  845. }
  846. func waitForStream(c *gin.Context, ch chan interface{}) {
  847. c.Header("Content-Type", "application/json")
  848. for resp := range ch {
  849. switch r := resp.(type) {
  850. case api.ProgressResponse:
  851. if r.Status == "success" {
  852. c.JSON(http.StatusOK, r)
  853. return
  854. }
  855. case gin.H:
  856. if errorMsg, ok := r["error"].(string); ok {
  857. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  858. return
  859. } else {
  860. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  861. return
  862. }
  863. default:
  864. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  865. return
  866. }
  867. }
  868. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  869. }
  870. func streamResponse(c *gin.Context, ch chan any) {
  871. c.Header("Content-Type", "application/x-ndjson")
  872. c.Stream(func(w io.Writer) bool {
  873. val, ok := <-ch
  874. if !ok {
  875. return false
  876. }
  877. bts, err := json.Marshal(val)
  878. if err != nil {
  879. slog.Info(fmt.Sprintf("streamResponse: json.Marshal failed with %s", err))
  880. return false
  881. }
  882. // Delineate chunks with new-line delimiter
  883. bts = append(bts, '\n')
  884. if _, err := w.Write(bts); err != nil {
  885. slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
  886. return false
  887. }
  888. return true
  889. })
  890. }
  891. func ChatHandler(c *gin.Context) {
  892. loaded.mu.Lock()
  893. defer loaded.mu.Unlock()
  894. checkpointStart := time.Now()
  895. var req api.ChatRequest
  896. err := c.ShouldBindJSON(&req)
  897. switch {
  898. case errors.Is(err, io.EOF):
  899. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  900. return
  901. case err != nil:
  902. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  903. return
  904. }
  905. // validate the request
  906. switch {
  907. case req.Model == "":
  908. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  909. return
  910. case len(req.Format) > 0 && req.Format != "json":
  911. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
  912. return
  913. }
  914. model, err := GetModel(req.Model)
  915. if err != nil {
  916. var pErr *fs.PathError
  917. if errors.As(err, &pErr) {
  918. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  919. return
  920. }
  921. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  922. return
  923. }
  924. opts, err := modelOptions(model, req.Options)
  925. if err != nil {
  926. if errors.Is(err, api.ErrInvalidOpts) {
  927. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  928. return
  929. }
  930. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  931. return
  932. }
  933. var sessionDuration time.Duration
  934. if req.KeepAlive == nil {
  935. sessionDuration = defaultSessionDuration
  936. } else {
  937. sessionDuration = req.KeepAlive.Duration
  938. }
  939. if err := load(c, model, opts, sessionDuration); err != nil {
  940. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  941. return
  942. }
  943. // an empty request loads the model
  944. if len(req.Messages) == 0 {
  945. resp := api.ChatResponse{
  946. CreatedAt: time.Now().UTC(),
  947. Model: req.Model,
  948. Done: true,
  949. Message: api.Message{Role: "assistant"},
  950. }
  951. c.JSON(http.StatusOK, resp)
  952. return
  953. }
  954. checkpointLoaded := time.Now()
  955. chat, err := model.ChatPrompts(req.Messages)
  956. if err != nil {
  957. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  958. return
  959. }
  960. prompt, err := trimmedPrompt(c.Request.Context(), chat, model)
  961. if err != nil {
  962. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  963. return
  964. }
  965. slog.Debug(fmt.Sprintf("prompt: %s", prompt))
  966. ch := make(chan any)
  967. go func() {
  968. defer close(ch)
  969. fn := func(r llm.PredictResult) {
  970. // Update model expiration
  971. loaded.expireAt = time.Now().Add(sessionDuration)
  972. loaded.expireTimer.Reset(sessionDuration)
  973. resp := api.ChatResponse{
  974. Model: req.Model,
  975. CreatedAt: time.Now().UTC(),
  976. Message: api.Message{Role: "assistant", Content: r.Content},
  977. Done: r.Done,
  978. Metrics: api.Metrics{
  979. PromptEvalCount: r.PromptEvalCount,
  980. PromptEvalDuration: r.PromptEvalDuration,
  981. EvalCount: r.EvalCount,
  982. EvalDuration: r.EvalDuration,
  983. },
  984. }
  985. if r.Done {
  986. resp.TotalDuration = time.Since(checkpointStart)
  987. resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  988. }
  989. ch <- resp
  990. }
  991. // Start prediction
  992. predictReq := llm.PredictOpts{
  993. Prompt: prompt,
  994. Format: req.Format,
  995. Images: chat.CurrentImages,
  996. Options: opts,
  997. }
  998. if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
  999. ch <- gin.H{"error": err.Error()}
  1000. }
  1001. }()
  1002. if req.Stream != nil && !*req.Stream {
  1003. // Accumulate responses into the final response
  1004. var final api.ChatResponse
  1005. var sb strings.Builder
  1006. for resp := range ch {
  1007. switch r := resp.(type) {
  1008. case api.ChatResponse:
  1009. sb.WriteString(r.Message.Content)
  1010. final = r
  1011. case gin.H:
  1012. if errorMsg, ok := r["error"].(string); ok {
  1013. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  1014. return
  1015. } else {
  1016. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in response"})
  1017. return
  1018. }
  1019. default:
  1020. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error"})
  1021. return
  1022. }
  1023. }
  1024. final.Message = api.Message{Role: "assistant", Content: sb.String()}
  1025. c.JSON(http.StatusOK, final)
  1026. return
  1027. }
  1028. streamResponse(c, ch)
  1029. }
  1030. // promptInfo stores the variables used to template a prompt, and the token length of the resulting template for some model
  1031. type promptInfo struct {
  1032. vars PromptVars
  1033. tokenLen int
  1034. }
  1035. // trimmedPrompt builds a prompt to send to a running model. It ensures the prompt fits within the max context length,
  1036. // while preserving the most recent system message.
  1037. func trimmedPrompt(ctx context.Context, chat *ChatHistory, model *Model) (string, error) {
  1038. if len(chat.Prompts) == 0 {
  1039. return "", nil
  1040. }
  1041. var promptsToAdd []promptInfo
  1042. var totalTokenLength int
  1043. var systemPromptIncluded bool
  1044. // reverse iterate through the prompts to build the prompt string in a way that fits the max context length
  1045. for i := len(chat.Prompts) - 1; i >= 0; i-- {
  1046. promptText, err := promptString(model, chat.Prompts[i], i == len(chat.Prompts)-1)
  1047. if err != nil {
  1048. return "", err
  1049. }
  1050. encodedTokens, err := loaded.runner.Encode(ctx, promptText)
  1051. if err != nil {
  1052. return "", err
  1053. }
  1054. if totalTokenLength+len(encodedTokens) > loaded.NumCtx && i != len(chat.Prompts)-1 {
  1055. break // reached max context length, stop adding more prompts
  1056. }
  1057. totalTokenLength += len(encodedTokens)
  1058. systemPromptIncluded = systemPromptIncluded || chat.Prompts[i].System != ""
  1059. promptsToAdd = append(promptsToAdd, promptInfo{vars: chat.Prompts[i], tokenLen: len(encodedTokens)})
  1060. }
  1061. // ensure the system prompt is included, if not already
  1062. if chat.LastSystem != "" && !systemPromptIncluded {
  1063. var err error
  1064. promptsToAdd, err = includeSystemPrompt(ctx, chat.LastSystem, totalTokenLength, promptsToAdd)
  1065. if err != nil {
  1066. return "", err
  1067. }
  1068. }
  1069. promptsToAdd[len(promptsToAdd)-1].vars.First = true
  1070. // construct the final prompt string from the prompts which fit within the context window
  1071. var result string
  1072. for i, prompt := range promptsToAdd {
  1073. promptText, err := promptString(model, prompt.vars, i == 0)
  1074. if err != nil {
  1075. return "", err
  1076. }
  1077. result = promptText + result
  1078. }
  1079. return result, nil
  1080. }
  1081. // promptString applies the model template to the prompt
  1082. func promptString(model *Model, vars PromptVars, isMostRecent bool) (string, error) {
  1083. if isMostRecent {
  1084. p, err := model.PreResponsePrompt(vars)
  1085. if err != nil {
  1086. return "", fmt.Errorf("pre-response template: %w", err)
  1087. }
  1088. return p, nil
  1089. }
  1090. p, err := Prompt(model.Template, vars)
  1091. if err != nil {
  1092. return "", err
  1093. }
  1094. return p, nil
  1095. }
  1096. // includeSystemPrompt adjusts the prompts to include the system prompt.
  1097. func includeSystemPrompt(ctx context.Context, systemPrompt string, totalTokenLength int, promptsToAdd []promptInfo) ([]promptInfo, error) {
  1098. systemTokens, err := loaded.runner.Encode(ctx, systemPrompt)
  1099. if err != nil {
  1100. return nil, err
  1101. }
  1102. for i := len(promptsToAdd) - 1; i >= 0; i-- {
  1103. if totalTokenLength+len(systemTokens) <= loaded.NumCtx {
  1104. promptsToAdd[i].vars.System = systemPrompt
  1105. return promptsToAdd[:i+1], nil
  1106. }
  1107. totalTokenLength -= promptsToAdd[i].tokenLen
  1108. }
  1109. // if got here, system did not fit anywhere, so return the most recent prompt with the system message set
  1110. recent := promptsToAdd[len(promptsToAdd)-1]
  1111. recent.vars.System = systemPrompt
  1112. return []promptInfo{recent}, nil
  1113. }