routes.go 28 KB

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