routes.go 27 KB

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