routes.go 19 KB

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