routes.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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. 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. log.Printf("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. if req.Name == "" {
  358. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  359. return
  360. }
  361. ch := make(chan any)
  362. go func() {
  363. defer close(ch)
  364. fn := func(r api.ProgressResponse) {
  365. ch <- r
  366. }
  367. regOpts := &RegistryOptions{
  368. Insecure: req.Insecure,
  369. }
  370. ctx, cancel := context.WithCancel(c.Request.Context())
  371. defer cancel()
  372. if err := PullModel(ctx, req.Name, regOpts, fn); err != nil {
  373. ch <- gin.H{"error": err.Error()}
  374. }
  375. }()
  376. if req.Stream != nil && !*req.Stream {
  377. waitForStream(c, ch)
  378. return
  379. }
  380. streamResponse(c, ch)
  381. }
  382. func PushModelHandler(c *gin.Context) {
  383. var req api.PushRequest
  384. err := c.ShouldBindJSON(&req)
  385. switch {
  386. case errors.Is(err, io.EOF):
  387. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  388. return
  389. case err != nil:
  390. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  391. return
  392. }
  393. if req.Name == "" {
  394. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  395. return
  396. }
  397. ch := make(chan any)
  398. go func() {
  399. defer close(ch)
  400. fn := func(r api.ProgressResponse) {
  401. ch <- r
  402. }
  403. regOpts := &RegistryOptions{
  404. Insecure: req.Insecure,
  405. }
  406. ctx, cancel := context.WithCancel(c.Request.Context())
  407. defer cancel()
  408. if err := PushModel(ctx, req.Name, regOpts, fn); err != nil {
  409. ch <- gin.H{"error": err.Error()}
  410. }
  411. }()
  412. if req.Stream != nil && !*req.Stream {
  413. waitForStream(c, ch)
  414. return
  415. }
  416. streamResponse(c, ch)
  417. }
  418. func CreateModelHandler(c *gin.Context) {
  419. var req api.CreateRequest
  420. err := c.ShouldBindJSON(&req)
  421. switch {
  422. case errors.Is(err, io.EOF):
  423. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  424. return
  425. case err != nil:
  426. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  427. return
  428. }
  429. if req.Name == "" {
  430. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  431. return
  432. }
  433. if err := ParseModelPath(req.Name).Validate(); err != nil {
  434. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  435. return
  436. }
  437. if req.Path == "" && req.Modelfile == "" {
  438. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
  439. return
  440. }
  441. var modelfile io.Reader = strings.NewReader(req.Modelfile)
  442. if req.Path != "" && req.Modelfile == "" {
  443. mf, err := os.Open(req.Path)
  444. if err != nil {
  445. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
  446. return
  447. }
  448. defer mf.Close()
  449. modelfile = mf
  450. }
  451. commands, err := parser.Parse(modelfile)
  452. if err != nil {
  453. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  454. return
  455. }
  456. ch := make(chan any)
  457. go func() {
  458. defer close(ch)
  459. fn := func(resp api.ProgressResponse) {
  460. ch <- resp
  461. }
  462. ctx, cancel := context.WithCancel(c.Request.Context())
  463. defer cancel()
  464. if err := CreateModel(ctx, req.Name, filepath.Dir(req.Path), commands, fn); err != nil {
  465. ch <- gin.H{"error": err.Error()}
  466. }
  467. }()
  468. if req.Stream != nil && !*req.Stream {
  469. waitForStream(c, ch)
  470. return
  471. }
  472. streamResponse(c, ch)
  473. }
  474. func DeleteModelHandler(c *gin.Context) {
  475. var req api.DeleteRequest
  476. err := c.ShouldBindJSON(&req)
  477. switch {
  478. case errors.Is(err, io.EOF):
  479. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  480. return
  481. case err != nil:
  482. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  483. return
  484. }
  485. if req.Name == "" {
  486. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  487. return
  488. }
  489. if err := DeleteModel(req.Name); err != nil {
  490. if os.IsNotExist(err) {
  491. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  492. } else {
  493. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  494. }
  495. return
  496. }
  497. manifestsPath, err := GetManifestPath()
  498. if err != nil {
  499. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  500. return
  501. }
  502. if err := PruneDirectory(manifestsPath); err != nil {
  503. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  504. return
  505. }
  506. c.JSON(http.StatusOK, nil)
  507. }
  508. func ShowModelHandler(c *gin.Context) {
  509. var req api.ShowRequest
  510. err := c.ShouldBindJSON(&req)
  511. switch {
  512. case errors.Is(err, io.EOF):
  513. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  514. return
  515. case err != nil:
  516. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  517. return
  518. }
  519. switch {
  520. case req.Model == "" && req.Name == "":
  521. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  522. return
  523. case req.Model != "" && req.Name != "":
  524. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "both model and name are set"})
  525. return
  526. case req.Model == "" && req.Name != "":
  527. req.Model = req.Name
  528. }
  529. resp, err := GetModelInfo(req)
  530. if err != nil {
  531. if os.IsNotExist(err) {
  532. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  533. } else {
  534. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  535. }
  536. return
  537. }
  538. c.JSON(http.StatusOK, resp)
  539. }
  540. func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
  541. model, err := GetModel(req.Model)
  542. if err != nil {
  543. return nil, err
  544. }
  545. modelDetails := api.ModelDetails{
  546. Format: model.Config.ModelFormat,
  547. Family: model.Config.ModelFamily,
  548. Families: model.Config.ModelFamilies,
  549. ParameterSize: model.Config.ModelType,
  550. QuantizationLevel: model.Config.FileType,
  551. }
  552. if req.System != "" {
  553. model.System = req.System
  554. }
  555. if req.Template != "" {
  556. model.Template = req.Template
  557. }
  558. resp := &api.ShowResponse{
  559. License: strings.Join(model.License, "\n"),
  560. System: model.System,
  561. Template: model.Template,
  562. Details: modelDetails,
  563. }
  564. var params []string
  565. cs := 30
  566. for k, v := range model.Options {
  567. switch val := v.(type) {
  568. case string:
  569. params = append(params, fmt.Sprintf("%-*s %s", cs, k, val))
  570. case int:
  571. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(val)))
  572. case float64:
  573. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(val, 'f', 0, 64)))
  574. case bool:
  575. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(val)))
  576. case []interface{}:
  577. for _, nv := range val {
  578. switch nval := nv.(type) {
  579. case string:
  580. params = append(params, fmt.Sprintf("%-*s %s", cs, k, nval))
  581. case int:
  582. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(nval)))
  583. case float64:
  584. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(nval, 'f', 0, 64)))
  585. case bool:
  586. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(nval)))
  587. }
  588. }
  589. }
  590. }
  591. resp.Parameters = strings.Join(params, "\n")
  592. for k, v := range req.Options {
  593. if _, ok := req.Options[k]; ok {
  594. model.Options[k] = v
  595. }
  596. }
  597. mf, err := ShowModelfile(model)
  598. if err != nil {
  599. return nil, err
  600. }
  601. resp.Modelfile = mf
  602. return resp, nil
  603. }
  604. func ListModelsHandler(c *gin.Context) {
  605. models := make([]api.ModelResponse, 0)
  606. fp, err := GetManifestPath()
  607. if err != nil {
  608. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  609. return
  610. }
  611. modelResponse := func(modelName string) (api.ModelResponse, error) {
  612. model, err := GetModel(modelName)
  613. if err != nil {
  614. return api.ModelResponse{}, err
  615. }
  616. modelDetails := api.ModelDetails{
  617. Format: model.Config.ModelFormat,
  618. Family: model.Config.ModelFamily,
  619. Families: model.Config.ModelFamilies,
  620. ParameterSize: model.Config.ModelType,
  621. QuantizationLevel: model.Config.FileType,
  622. }
  623. return api.ModelResponse{
  624. Name: model.ShortName,
  625. Size: model.Size,
  626. Digest: model.Digest,
  627. Details: modelDetails,
  628. }, nil
  629. }
  630. walkFunc := func(path string, info os.FileInfo, _ error) error {
  631. if !info.IsDir() {
  632. dir, file := filepath.Split(path)
  633. dir = strings.Trim(strings.TrimPrefix(dir, fp), string(os.PathSeparator))
  634. tag := strings.Join([]string{dir, file}, ":")
  635. resp, err := modelResponse(tag)
  636. if err != nil {
  637. log.Printf("skipping file: %s", fp)
  638. return nil
  639. }
  640. resp.ModifiedAt = info.ModTime()
  641. models = append(models, resp)
  642. }
  643. return nil
  644. }
  645. if err := filepath.Walk(fp, walkFunc); err != nil {
  646. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  647. return
  648. }
  649. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  650. }
  651. func CopyModelHandler(c *gin.Context) {
  652. var req api.CopyRequest
  653. err := c.ShouldBindJSON(&req)
  654. switch {
  655. case errors.Is(err, io.EOF):
  656. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  657. return
  658. case err != nil:
  659. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  660. return
  661. }
  662. if req.Source == "" || req.Destination == "" {
  663. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
  664. return
  665. }
  666. if err := ParseModelPath(req.Destination).Validate(); err != nil {
  667. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  668. return
  669. }
  670. if err := CopyModel(req.Source, req.Destination); err != nil {
  671. if os.IsNotExist(err) {
  672. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  673. } else {
  674. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  675. }
  676. return
  677. }
  678. }
  679. func HeadBlobHandler(c *gin.Context) {
  680. path, err := GetBlobsPath(c.Param("digest"))
  681. if err != nil {
  682. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  683. return
  684. }
  685. if _, err := os.Stat(path); err != nil {
  686. c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("blob %q not found", c.Param("digest"))})
  687. return
  688. }
  689. c.Status(http.StatusOK)
  690. }
  691. func CreateBlobHandler(c *gin.Context) {
  692. layer, err := NewLayer(c.Request.Body, "")
  693. if err != nil {
  694. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  695. return
  696. }
  697. if layer.Digest != c.Param("digest") {
  698. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("digest mismatch, expected %q, got %q", c.Param("digest"), layer.Digest)})
  699. return
  700. }
  701. if _, err := layer.Commit(); err != nil {
  702. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  703. return
  704. }
  705. c.Status(http.StatusCreated)
  706. }
  707. var defaultAllowOrigins = []string{
  708. "localhost",
  709. "127.0.0.1",
  710. "0.0.0.0",
  711. }
  712. func NewServer() (*Server, error) {
  713. workDir, err := os.MkdirTemp("", "ollama")
  714. if err != nil {
  715. return nil, err
  716. }
  717. return &Server{
  718. WorkDir: workDir,
  719. }, nil
  720. }
  721. func (s *Server) GenerateRoutes() http.Handler {
  722. var origins []string
  723. if o := os.Getenv("OLLAMA_ORIGINS"); o != "" {
  724. origins = strings.Split(o, ",")
  725. }
  726. config := cors.DefaultConfig()
  727. config.AllowWildcard = true
  728. config.AllowOrigins = origins
  729. for _, allowOrigin := range defaultAllowOrigins {
  730. config.AllowOrigins = append(config.AllowOrigins,
  731. fmt.Sprintf("http://%s", allowOrigin),
  732. fmt.Sprintf("https://%s", allowOrigin),
  733. fmt.Sprintf("http://%s:*", allowOrigin),
  734. fmt.Sprintf("https://%s:*", allowOrigin),
  735. )
  736. }
  737. r := gin.Default()
  738. r.Use(
  739. cors.New(config),
  740. func(c *gin.Context) {
  741. c.Set("workDir", s.WorkDir)
  742. c.Next()
  743. },
  744. )
  745. r.POST("/api/pull", PullModelHandler)
  746. r.POST("/api/generate", GenerateHandler)
  747. r.POST("/api/chat", ChatHandler)
  748. r.POST("/api/embeddings", EmbeddingHandler)
  749. r.POST("/api/create", CreateModelHandler)
  750. r.POST("/api/push", PushModelHandler)
  751. r.POST("/api/copy", CopyModelHandler)
  752. r.DELETE("/api/delete", DeleteModelHandler)
  753. r.POST("/api/show", ShowModelHandler)
  754. r.POST("/api/blobs/:digest", CreateBlobHandler)
  755. r.HEAD("/api/blobs/:digest", HeadBlobHandler)
  756. for _, method := range []string{http.MethodGet, http.MethodHead} {
  757. r.Handle(method, "/", func(c *gin.Context) {
  758. c.String(http.StatusOK, "Ollama is running")
  759. })
  760. r.Handle(method, "/api/tags", ListModelsHandler)
  761. r.Handle(method, "/api/version", func(c *gin.Context) {
  762. c.JSON(http.StatusOK, gin.H{"version": version.Version})
  763. })
  764. }
  765. return r
  766. }
  767. func Serve(ln net.Listener) error {
  768. if noprune := os.Getenv("OLLAMA_NOPRUNE"); noprune == "" {
  769. // clean up unused layers and manifests
  770. if err := PruneLayers(); err != nil {
  771. return err
  772. }
  773. manifestsPath, err := GetManifestPath()
  774. if err != nil {
  775. return err
  776. }
  777. if err := PruneDirectory(manifestsPath); err != nil {
  778. return err
  779. }
  780. }
  781. s, err := NewServer()
  782. if err != nil {
  783. return err
  784. }
  785. r := s.GenerateRoutes()
  786. log.Printf("Listening on %s (version %s)", ln.Addr(), version.Version)
  787. srvr := &http.Server{
  788. Handler: r,
  789. }
  790. // listen for a ctrl+c and stop any loaded llm
  791. signals := make(chan os.Signal, 1)
  792. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  793. go func() {
  794. <-signals
  795. if loaded.runner != nil {
  796. loaded.runner.Close()
  797. }
  798. os.RemoveAll(s.WorkDir)
  799. os.Exit(0)
  800. }()
  801. if err := llm.Init(s.WorkDir); err != nil {
  802. return fmt.Errorf("unable to initialize llm library %w", err)
  803. }
  804. if runtime.GOOS == "linux" { // TODO - windows too
  805. // check compatibility to log warnings
  806. if _, err := gpu.CheckVRAM(); err != nil {
  807. log.Print(err.Error())
  808. }
  809. }
  810. return srvr.Serve(ln)
  811. }
  812. func waitForStream(c *gin.Context, ch chan interface{}) {
  813. c.Header("Content-Type", "application/json")
  814. for resp := range ch {
  815. switch r := resp.(type) {
  816. case api.ProgressResponse:
  817. if r.Status == "success" {
  818. c.JSON(http.StatusOK, r)
  819. return
  820. }
  821. case gin.H:
  822. if errorMsg, ok := r["error"].(string); ok {
  823. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  824. return
  825. } else {
  826. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  827. return
  828. }
  829. default:
  830. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  831. return
  832. }
  833. }
  834. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  835. }
  836. func streamResponse(c *gin.Context, ch chan any) {
  837. c.Header("Content-Type", "application/x-ndjson")
  838. c.Stream(func(w io.Writer) bool {
  839. val, ok := <-ch
  840. if !ok {
  841. return false
  842. }
  843. bts, err := json.Marshal(val)
  844. if err != nil {
  845. log.Printf("streamResponse: json.Marshal failed with %s", err)
  846. return false
  847. }
  848. // Delineate chunks with new-line delimiter
  849. bts = append(bts, '\n')
  850. if _, err := w.Write(bts); err != nil {
  851. log.Printf("streamResponse: w.Write failed with %s", err)
  852. return false
  853. }
  854. return true
  855. })
  856. }
  857. func ChatHandler(c *gin.Context) {
  858. loaded.mu.Lock()
  859. defer loaded.mu.Unlock()
  860. checkpointStart := time.Now()
  861. var req api.ChatRequest
  862. err := c.ShouldBindJSON(&req)
  863. switch {
  864. case errors.Is(err, io.EOF):
  865. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  866. return
  867. case err != nil:
  868. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  869. return
  870. }
  871. // validate the request
  872. switch {
  873. case req.Model == "":
  874. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  875. return
  876. case len(req.Format) > 0 && req.Format != "json":
  877. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
  878. return
  879. }
  880. model, err := GetModel(req.Model)
  881. if err != nil {
  882. var pErr *fs.PathError
  883. if errors.As(err, &pErr) {
  884. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  885. return
  886. }
  887. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  888. return
  889. }
  890. opts, err := modelOptions(model, req.Options)
  891. if err != nil {
  892. if errors.Is(err, api.ErrInvalidOpts) {
  893. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  894. return
  895. }
  896. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  897. return
  898. }
  899. sessionDuration := defaultSessionDuration
  900. if err := load(c, model, opts, sessionDuration); err != nil {
  901. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  902. return
  903. }
  904. // an empty request loads the model
  905. if len(req.Messages) == 0 {
  906. c.JSON(http.StatusOK, api.ChatResponse{CreatedAt: time.Now().UTC(), Model: req.Model, Done: true, Message: api.Message{Role: "assistant"}})
  907. return
  908. }
  909. checkpointLoaded := time.Now()
  910. prompt, images, err := model.ChatPrompt(req.Messages)
  911. if err != nil {
  912. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  913. return
  914. }
  915. ch := make(chan any)
  916. go func() {
  917. defer close(ch)
  918. fn := func(r llm.PredictResult) {
  919. // Update model expiration
  920. loaded.expireAt = time.Now().Add(sessionDuration)
  921. loaded.expireTimer.Reset(sessionDuration)
  922. resp := api.ChatResponse{
  923. Model: req.Model,
  924. CreatedAt: time.Now().UTC(),
  925. Message: api.Message{Role: "assistant", Content: r.Content},
  926. Done: r.Done,
  927. Metrics: api.Metrics{
  928. PromptEvalCount: r.PromptEvalCount,
  929. PromptEvalDuration: r.PromptEvalDuration,
  930. EvalCount: r.EvalCount,
  931. EvalDuration: r.EvalDuration,
  932. },
  933. }
  934. if r.Done {
  935. resp.TotalDuration = time.Since(checkpointStart)
  936. resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  937. }
  938. ch <- resp
  939. }
  940. // Start prediction
  941. predictReq := llm.PredictOpts{
  942. Prompt: prompt,
  943. Format: req.Format,
  944. Images: images,
  945. Options: opts,
  946. }
  947. if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
  948. ch <- gin.H{"error": err.Error()}
  949. }
  950. }()
  951. if req.Stream != nil && !*req.Stream {
  952. // Accumulate responses into the final response
  953. var final api.ChatResponse
  954. var sb strings.Builder
  955. for resp := range ch {
  956. switch r := resp.(type) {
  957. case api.ChatResponse:
  958. sb.WriteString(r.Message.Content)
  959. final = r
  960. case gin.H:
  961. if errorMsg, ok := r["error"].(string); ok {
  962. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  963. return
  964. } else {
  965. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in response"})
  966. return
  967. }
  968. default:
  969. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error"})
  970. return
  971. }
  972. }
  973. final.Message = api.Message{Role: "assistant", Content: sb.String()}
  974. c.JSON(http.StatusOK, final)
  975. return
  976. }
  977. streamResponse(c, ch)
  978. }