routes.go 27 KB

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