routes.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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(ctx context.Context, workDir string, model *Model, reqOpts map[string]interface{}, sessionDuration time.Duration) error {
  51. opts := api.DefaultOptions()
  52. if err := opts.FromMap(model.Options); err != nil {
  53. log.Printf("could not load model options: %v", err)
  54. return err
  55. }
  56. if err := opts.FromMap(reqOpts); err != nil {
  57. return err
  58. }
  59. // check if the loaded model is still running in a subprocess, in case something unexpected happened
  60. if loaded.runner != nil {
  61. if err := loaded.runner.Ping(ctx); err != nil {
  62. log.Print("loaded llm process not responding, closing now")
  63. // the subprocess is no longer running, so close it
  64. loaded.runner.Close()
  65. loaded.runner = nil
  66. loaded.Model = nil
  67. loaded.Options = nil
  68. }
  69. }
  70. needLoad := loaded.runner == nil || // is there a model loaded?
  71. loaded.ModelPath != model.ModelPath || // has the base model changed?
  72. !reflect.DeepEqual(loaded.AdapterPaths, model.AdapterPaths) || // have the adapters changed?
  73. !reflect.DeepEqual(loaded.Options.Runner, opts.Runner) // have the runner options changed?
  74. if needLoad {
  75. if loaded.runner != nil {
  76. log.Println("changing loaded model")
  77. loaded.runner.Close()
  78. loaded.runner = nil
  79. loaded.Model = nil
  80. loaded.Options = nil
  81. }
  82. llmRunner, err := llm.New(workDir, model.ModelPath, model.AdapterPaths, opts)
  83. if err != nil {
  84. // some older models are not compatible with newer versions of llama.cpp
  85. // show a generalized compatibility error until there is a better way to
  86. // check for model compatibility
  87. if strings.Contains(err.Error(), "failed to load model") {
  88. 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)
  89. }
  90. return err
  91. }
  92. loaded.Model = model
  93. loaded.runner = llmRunner
  94. loaded.Options = &opts
  95. }
  96. // update options for the loaded llm
  97. // TODO(mxyng): this isn't thread safe, but it should be fine for now
  98. loaded.runner.SetOptions(opts)
  99. loaded.expireAt = time.Now().Add(sessionDuration)
  100. if loaded.expireTimer == nil {
  101. loaded.expireTimer = time.AfterFunc(sessionDuration, func() {
  102. loaded.mu.Lock()
  103. defer loaded.mu.Unlock()
  104. if time.Now().Before(loaded.expireAt) {
  105. return
  106. }
  107. if loaded.runner != nil {
  108. loaded.runner.Close()
  109. }
  110. loaded.runner = nil
  111. loaded.Model = nil
  112. loaded.Options = nil
  113. })
  114. }
  115. loaded.expireTimer.Reset(sessionDuration)
  116. return nil
  117. }
  118. func GenerateHandler(c *gin.Context) {
  119. loaded.mu.Lock()
  120. defer loaded.mu.Unlock()
  121. checkpointStart := time.Now()
  122. var req api.GenerateRequest
  123. err := c.ShouldBindJSON(&req)
  124. switch {
  125. case errors.Is(err, io.EOF):
  126. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  127. return
  128. case err != nil:
  129. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  130. return
  131. }
  132. // validate the request
  133. switch {
  134. case req.Model == "":
  135. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  136. return
  137. case len(req.Format) > 0 && req.Format != "json":
  138. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
  139. return
  140. case req.Raw && (req.Template != "" || req.System != "" || len(req.Context) > 0):
  141. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "raw mode does not support template, system, or context"})
  142. return
  143. }
  144. model, err := GetModel(req.Model)
  145. if err != nil {
  146. var pErr *fs.PathError
  147. if errors.As(err, &pErr) {
  148. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  149. return
  150. }
  151. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  152. return
  153. }
  154. workDir := c.GetString("workDir")
  155. // TODO: set this duration from the request if specified
  156. sessionDuration := defaultSessionDuration
  157. if err := load(c.Request.Context(), workDir, model, req.Options, sessionDuration); err != nil {
  158. if errors.Is(err, api.ErrInvalidOpts) {
  159. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  160. return
  161. }
  162. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  163. return
  164. }
  165. checkpointLoaded := time.Now()
  166. prompt := req.Prompt
  167. if !req.Raw {
  168. prompt, err = model.Prompt(req)
  169. if err != nil {
  170. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  171. return
  172. }
  173. }
  174. ch := make(chan any)
  175. go func() {
  176. defer close(ch)
  177. // an empty request loads the model
  178. if req.Prompt == "" && req.Template == "" && req.System == "" {
  179. ch <- api.GenerateResponse{CreatedAt: time.Now().UTC(), Model: req.Model, Done: true}
  180. return
  181. }
  182. fn := func(r api.GenerateResponse) {
  183. loaded.expireAt = time.Now().Add(sessionDuration)
  184. loaded.expireTimer.Reset(sessionDuration)
  185. r.Model = req.Model
  186. r.CreatedAt = time.Now().UTC()
  187. if r.Done {
  188. r.TotalDuration = time.Since(checkpointStart)
  189. r.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  190. }
  191. if req.Raw {
  192. // in raw mode the client must manage history on their own
  193. r.Context = nil
  194. }
  195. ch <- r
  196. }
  197. if err := loaded.runner.Predict(c.Request.Context(), req.Context, prompt, req.Format, fn); err != nil {
  198. ch <- gin.H{"error": err.Error()}
  199. }
  200. }()
  201. if req.Stream != nil && !*req.Stream {
  202. var response api.GenerateResponse
  203. generated := ""
  204. for resp := range ch {
  205. if r, ok := resp.(api.GenerateResponse); ok {
  206. generated += r.Response
  207. response = r
  208. } else {
  209. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  210. return
  211. }
  212. }
  213. response.Response = generated
  214. c.JSON(http.StatusOK, response)
  215. return
  216. }
  217. streamResponse(c, ch)
  218. }
  219. func EmbeddingHandler(c *gin.Context) {
  220. loaded.mu.Lock()
  221. defer loaded.mu.Unlock()
  222. var req api.EmbeddingRequest
  223. err := c.ShouldBindJSON(&req)
  224. switch {
  225. case errors.Is(err, io.EOF):
  226. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  227. return
  228. case err != nil:
  229. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  230. return
  231. }
  232. if req.Model == "" {
  233. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  234. return
  235. }
  236. model, err := GetModel(req.Model)
  237. if err != nil {
  238. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  239. return
  240. }
  241. workDir := c.GetString("workDir")
  242. if err := load(c.Request.Context(), workDir, model, req.Options, 5*time.Minute); err != nil {
  243. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  244. return
  245. }
  246. if !loaded.Options.EmbeddingOnly {
  247. c.JSON(http.StatusBadRequest, gin.H{"error": "embedding option must be set to true"})
  248. return
  249. }
  250. embedding, err := loaded.runner.Embedding(c.Request.Context(), req.Prompt)
  251. if err != nil {
  252. log.Printf("embedding generation failed: %v", err)
  253. c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
  254. return
  255. }
  256. resp := api.EmbeddingResponse{
  257. Embedding: embedding,
  258. }
  259. c.JSON(http.StatusOK, resp)
  260. }
  261. func PullModelHandler(c *gin.Context) {
  262. var req api.PullRequest
  263. err := c.ShouldBindJSON(&req)
  264. switch {
  265. case errors.Is(err, io.EOF):
  266. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  267. return
  268. case err != nil:
  269. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  270. return
  271. }
  272. if req.Name == "" {
  273. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  274. return
  275. }
  276. ch := make(chan any)
  277. go func() {
  278. defer close(ch)
  279. fn := func(r api.ProgressResponse) {
  280. ch <- r
  281. }
  282. regOpts := &RegistryOptions{
  283. Insecure: req.Insecure,
  284. }
  285. ctx, cancel := context.WithCancel(c.Request.Context())
  286. defer cancel()
  287. if err := PullModel(ctx, req.Name, regOpts, fn); err != nil {
  288. ch <- gin.H{"error": err.Error()}
  289. }
  290. }()
  291. if req.Stream != nil && !*req.Stream {
  292. waitForStream(c, ch)
  293. return
  294. }
  295. streamResponse(c, ch)
  296. }
  297. func PushModelHandler(c *gin.Context) {
  298. var req api.PushRequest
  299. err := c.ShouldBindJSON(&req)
  300. switch {
  301. case errors.Is(err, io.EOF):
  302. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  303. return
  304. case err != nil:
  305. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  306. return
  307. }
  308. if req.Name == "" {
  309. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  310. return
  311. }
  312. ch := make(chan any)
  313. go func() {
  314. defer close(ch)
  315. fn := func(r api.ProgressResponse) {
  316. ch <- r
  317. }
  318. regOpts := &RegistryOptions{
  319. Insecure: req.Insecure,
  320. }
  321. ctx, cancel := context.WithCancel(c.Request.Context())
  322. defer cancel()
  323. if err := PushModel(ctx, req.Name, regOpts, fn); err != nil {
  324. ch <- gin.H{"error": err.Error()}
  325. }
  326. }()
  327. if req.Stream != nil && !*req.Stream {
  328. waitForStream(c, ch)
  329. return
  330. }
  331. streamResponse(c, ch)
  332. }
  333. func CreateModelHandler(c *gin.Context) {
  334. var req api.CreateRequest
  335. err := c.ShouldBindJSON(&req)
  336. switch {
  337. case errors.Is(err, io.EOF):
  338. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  339. return
  340. case err != nil:
  341. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  342. return
  343. }
  344. if req.Name == "" {
  345. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  346. return
  347. }
  348. if req.Path == "" && req.Modelfile == "" {
  349. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
  350. return
  351. }
  352. var modelfile io.Reader = strings.NewReader(req.Modelfile)
  353. if req.Path != "" && req.Modelfile == "" {
  354. bin, err := os.Open(req.Path)
  355. if err != nil {
  356. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
  357. return
  358. }
  359. defer bin.Close()
  360. modelfile = bin
  361. }
  362. commands, err := parser.Parse(modelfile)
  363. if err != nil {
  364. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  365. return
  366. }
  367. ch := make(chan any)
  368. go func() {
  369. defer close(ch)
  370. fn := func(resp api.ProgressResponse) {
  371. ch <- resp
  372. }
  373. ctx, cancel := context.WithCancel(c.Request.Context())
  374. defer cancel()
  375. if err := CreateModel(ctx, req.Name, commands, fn); err != nil {
  376. ch <- gin.H{"error": err.Error()}
  377. }
  378. }()
  379. if req.Stream != nil && !*req.Stream {
  380. waitForStream(c, ch)
  381. return
  382. }
  383. streamResponse(c, ch)
  384. }
  385. func DeleteModelHandler(c *gin.Context) {
  386. var req api.DeleteRequest
  387. err := c.ShouldBindJSON(&req)
  388. switch {
  389. case errors.Is(err, io.EOF):
  390. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  391. return
  392. case err != nil:
  393. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  394. return
  395. }
  396. if req.Name == "" {
  397. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  398. return
  399. }
  400. if err := DeleteModel(req.Name); err != nil {
  401. if os.IsNotExist(err) {
  402. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  403. } else {
  404. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  405. }
  406. return
  407. }
  408. manifestsPath, err := GetManifestPath()
  409. if err != nil {
  410. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  411. return
  412. }
  413. if err := PruneDirectory(manifestsPath); err != nil {
  414. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  415. return
  416. }
  417. c.JSON(http.StatusOK, nil)
  418. }
  419. func ShowModelHandler(c *gin.Context) {
  420. var req api.ShowRequest
  421. err := c.ShouldBindJSON(&req)
  422. switch {
  423. case errors.Is(err, io.EOF):
  424. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  425. return
  426. case err != nil:
  427. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  428. return
  429. }
  430. if req.Name == "" {
  431. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  432. return
  433. }
  434. resp, err := GetModelInfo(req.Name)
  435. if err != nil {
  436. if os.IsNotExist(err) {
  437. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  438. } else {
  439. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  440. }
  441. return
  442. }
  443. c.JSON(http.StatusOK, resp)
  444. }
  445. func GetModelInfo(name string) (*api.ShowResponse, error) {
  446. model, err := GetModel(name)
  447. if err != nil {
  448. return nil, err
  449. }
  450. resp := &api.ShowResponse{
  451. License: strings.Join(model.License, "\n"),
  452. System: model.System,
  453. Template: model.Template,
  454. }
  455. mf, err := ShowModelfile(model)
  456. if err != nil {
  457. return nil, err
  458. }
  459. resp.Modelfile = mf
  460. var params []string
  461. cs := 30
  462. for k, v := range model.Options {
  463. switch val := v.(type) {
  464. case string:
  465. params = append(params, fmt.Sprintf("%-*s %s", cs, k, val))
  466. case int:
  467. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(val)))
  468. case float64:
  469. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(val, 'f', 0, 64)))
  470. case bool:
  471. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(val)))
  472. case []interface{}:
  473. for _, nv := range val {
  474. switch nval := nv.(type) {
  475. case string:
  476. params = append(params, fmt.Sprintf("%-*s %s", cs, k, nval))
  477. case int:
  478. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(nval)))
  479. case float64:
  480. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(nval, 'f', 0, 64)))
  481. case bool:
  482. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(nval)))
  483. }
  484. }
  485. }
  486. }
  487. resp.Parameters = strings.Join(params, "\n")
  488. return resp, nil
  489. }
  490. func ListModelsHandler(c *gin.Context) {
  491. models := make([]api.ModelResponse, 0)
  492. fp, err := GetManifestPath()
  493. if err != nil {
  494. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  495. return
  496. }
  497. walkFunc := func(path string, info os.FileInfo, _ error) error {
  498. if !info.IsDir() {
  499. dir, file := filepath.Split(path)
  500. dir = strings.Trim(strings.TrimPrefix(dir, fp), string(os.PathSeparator))
  501. tag := strings.Join([]string{dir, file}, ":")
  502. mp := ParseModelPath(tag)
  503. manifest, digest, err := GetManifest(mp)
  504. if err != nil {
  505. log.Printf("skipping file: %s", fp)
  506. return nil
  507. }
  508. models = append(models, api.ModelResponse{
  509. Name: mp.GetShortTagname(),
  510. Size: manifest.GetTotalSize(),
  511. Digest: digest,
  512. ModifiedAt: info.ModTime(),
  513. })
  514. }
  515. return nil
  516. }
  517. if err := filepath.Walk(fp, walkFunc); err != nil {
  518. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  519. return
  520. }
  521. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  522. }
  523. func CopyModelHandler(c *gin.Context) {
  524. var req api.CopyRequest
  525. err := c.ShouldBindJSON(&req)
  526. switch {
  527. case errors.Is(err, io.EOF):
  528. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  529. return
  530. case err != nil:
  531. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  532. return
  533. }
  534. if req.Source == "" || req.Destination == "" {
  535. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
  536. return
  537. }
  538. if err := CopyModel(req.Source, req.Destination); err != nil {
  539. if os.IsNotExist(err) {
  540. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  541. } else {
  542. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  543. }
  544. return
  545. }
  546. }
  547. var defaultAllowOrigins = []string{
  548. "localhost",
  549. "127.0.0.1",
  550. "0.0.0.0",
  551. }
  552. func Serve(ln net.Listener, allowOrigins []string) error {
  553. if noprune := os.Getenv("OLLAMA_NOPRUNE"); noprune == "" {
  554. // clean up unused layers and manifests
  555. if err := PruneLayers(); err != nil {
  556. return err
  557. }
  558. manifestsPath, err := GetManifestPath()
  559. if err != nil {
  560. return err
  561. }
  562. if err := PruneDirectory(manifestsPath); err != nil {
  563. return err
  564. }
  565. }
  566. config := cors.DefaultConfig()
  567. config.AllowWildcard = true
  568. config.AllowOrigins = allowOrigins
  569. for _, allowOrigin := range defaultAllowOrigins {
  570. config.AllowOrigins = append(config.AllowOrigins,
  571. fmt.Sprintf("http://%s", allowOrigin),
  572. fmt.Sprintf("https://%s", allowOrigin),
  573. fmt.Sprintf("http://%s:*", allowOrigin),
  574. fmt.Sprintf("https://%s:*", allowOrigin),
  575. )
  576. }
  577. workDir, err := os.MkdirTemp("", "ollama")
  578. if err != nil {
  579. return err
  580. }
  581. defer os.RemoveAll(workDir)
  582. r := gin.Default()
  583. r.Use(
  584. cors.New(config),
  585. func(c *gin.Context) {
  586. c.Set("workDir", workDir)
  587. c.Next()
  588. },
  589. )
  590. r.POST("/api/pull", PullModelHandler)
  591. r.POST("/api/generate", GenerateHandler)
  592. r.POST("/api/embeddings", EmbeddingHandler)
  593. r.POST("/api/create", CreateModelHandler)
  594. r.POST("/api/push", PushModelHandler)
  595. r.POST("/api/copy", CopyModelHandler)
  596. r.DELETE("/api/delete", DeleteModelHandler)
  597. r.POST("/api/show", ShowModelHandler)
  598. for _, method := range []string{http.MethodGet, http.MethodHead} {
  599. r.Handle(method, "/", func(c *gin.Context) {
  600. c.String(http.StatusOK, "Ollama is running")
  601. })
  602. r.Handle(method, "/api/tags", ListModelsHandler)
  603. }
  604. log.Printf("Listening on %s (version %s)", ln.Addr(), version.Version)
  605. s := &http.Server{
  606. Handler: r,
  607. }
  608. // listen for a ctrl+c and stop any loaded llm
  609. signals := make(chan os.Signal, 1)
  610. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  611. go func() {
  612. <-signals
  613. if loaded.runner != nil {
  614. loaded.runner.Close()
  615. }
  616. os.RemoveAll(workDir)
  617. os.Exit(0)
  618. }()
  619. if runtime.GOOS == "linux" {
  620. // check compatibility to log warnings
  621. if _, err := llm.CheckVRAM(); err != nil {
  622. log.Printf("Warning: GPU support may not be enabled, check you have installed GPU drivers: %v", err)
  623. }
  624. }
  625. return s.Serve(ln)
  626. }
  627. func waitForStream(c *gin.Context, ch chan interface{}) {
  628. c.Header("Content-Type", "application/json")
  629. for resp := range ch {
  630. switch r := resp.(type) {
  631. case api.ProgressResponse:
  632. if r.Status == "success" {
  633. c.JSON(http.StatusOK, r)
  634. return
  635. }
  636. case gin.H:
  637. if errorMsg, ok := r["error"].(string); ok {
  638. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  639. return
  640. } else {
  641. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  642. return
  643. }
  644. default:
  645. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  646. return
  647. }
  648. }
  649. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  650. }
  651. func streamResponse(c *gin.Context, ch chan any) {
  652. c.Header("Content-Type", "application/x-ndjson")
  653. c.Stream(func(w io.Writer) bool {
  654. val, ok := <-ch
  655. if !ok {
  656. return false
  657. }
  658. bts, err := json.Marshal(val)
  659. if err != nil {
  660. log.Printf("streamResponse: json.Marshal failed with %s", err)
  661. return false
  662. }
  663. // Delineate chunks with new-line delimiter
  664. bts = append(bts, '\n')
  665. if _, err := w.Write(bts); err != nil {
  666. log.Printf("streamResponse: w.Write failed with %s", err)
  667. return false
  668. }
  669. return true
  670. })
  671. }