routes.go 18 KB

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