routes.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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 := context.Background()
  306. if err := PushModel(ctx, req.Name, regOpts, fn); err != nil {
  307. ch <- gin.H{"error": err.Error()}
  308. }
  309. }()
  310. if req.Stream != nil && !*req.Stream {
  311. waitForStream(c, ch)
  312. return
  313. }
  314. streamResponse(c, ch)
  315. }
  316. func CreateModelHandler(c *gin.Context) {
  317. var req api.CreateRequest
  318. err := c.ShouldBindJSON(&req)
  319. switch {
  320. case errors.Is(err, io.EOF):
  321. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  322. return
  323. case err != nil:
  324. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  325. return
  326. }
  327. if req.Name == "" || req.Path == "" {
  328. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name and path are required"})
  329. return
  330. }
  331. ch := make(chan any)
  332. go func() {
  333. defer close(ch)
  334. fn := func(resp api.ProgressResponse) {
  335. ch <- resp
  336. }
  337. ctx, cancel := context.WithCancel(c.Request.Context())
  338. defer cancel()
  339. if err := CreateModel(ctx, req.Name, req.Path, fn); err != nil {
  340. ch <- gin.H{"error": err.Error()}
  341. }
  342. }()
  343. if req.Stream != nil && !*req.Stream {
  344. waitForStream(c, ch)
  345. return
  346. }
  347. streamResponse(c, ch)
  348. }
  349. func DeleteModelHandler(c *gin.Context) {
  350. var req api.DeleteRequest
  351. err := c.ShouldBindJSON(&req)
  352. switch {
  353. case errors.Is(err, io.EOF):
  354. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  355. return
  356. case err != nil:
  357. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  358. return
  359. }
  360. if req.Name == "" {
  361. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  362. return
  363. }
  364. if err := DeleteModel(req.Name); err != nil {
  365. if os.IsNotExist(err) {
  366. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  367. } else {
  368. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  369. }
  370. return
  371. }
  372. manifestsPath, err := GetManifestPath()
  373. if err != nil {
  374. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  375. return
  376. }
  377. if err := PruneDirectory(manifestsPath); err != nil {
  378. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  379. return
  380. }
  381. c.JSON(http.StatusOK, nil)
  382. }
  383. func ShowModelHandler(c *gin.Context) {
  384. var req api.ShowRequest
  385. err := c.ShouldBindJSON(&req)
  386. switch {
  387. case errors.Is(err, io.EOF):
  388. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  389. return
  390. case err != nil:
  391. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  392. return
  393. }
  394. if req.Name == "" {
  395. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  396. return
  397. }
  398. resp, err := GetModelInfo(req.Name)
  399. if err != nil {
  400. if os.IsNotExist(err) {
  401. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  402. } else {
  403. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  404. }
  405. return
  406. }
  407. c.JSON(http.StatusOK, resp)
  408. }
  409. func GetModelInfo(name string) (*api.ShowResponse, error) {
  410. model, err := GetModel(name)
  411. if err != nil {
  412. return nil, err
  413. }
  414. resp := &api.ShowResponse{
  415. License: strings.Join(model.License, "\n"),
  416. System: model.System,
  417. Template: model.Template,
  418. }
  419. mf, err := ShowModelfile(model)
  420. if err != nil {
  421. return nil, err
  422. }
  423. resp.Modelfile = mf
  424. var params []string
  425. cs := 30
  426. for k, v := range model.Options {
  427. switch val := v.(type) {
  428. case string:
  429. params = append(params, fmt.Sprintf("%-*s %s", cs, k, val))
  430. case int:
  431. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(val)))
  432. case float64:
  433. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(val, 'f', 0, 64)))
  434. case bool:
  435. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(val)))
  436. case []interface{}:
  437. for _, nv := range val {
  438. switch nval := nv.(type) {
  439. case string:
  440. params = append(params, fmt.Sprintf("%-*s %s", cs, k, nval))
  441. case int:
  442. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(nval)))
  443. case float64:
  444. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(nval, 'f', 0, 64)))
  445. case bool:
  446. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(nval)))
  447. }
  448. }
  449. }
  450. }
  451. resp.Parameters = strings.Join(params, "\n")
  452. return resp, nil
  453. }
  454. func ListModelsHandler(c *gin.Context) {
  455. models := make([]api.ModelResponse, 0)
  456. fp, err := GetManifestPath()
  457. if err != nil {
  458. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  459. return
  460. }
  461. walkFunc := func(path string, info os.FileInfo, _ error) error {
  462. if !info.IsDir() {
  463. dir, file := filepath.Split(path)
  464. dir = strings.Trim(strings.TrimPrefix(dir, fp), string(os.PathSeparator))
  465. tag := strings.Join([]string{dir, file}, ":")
  466. mp := ParseModelPath(tag)
  467. manifest, digest, err := GetManifest(mp)
  468. if err != nil {
  469. log.Printf("skipping file: %s", fp)
  470. return nil
  471. }
  472. models = append(models, api.ModelResponse{
  473. Name: mp.GetShortTagname(),
  474. Size: manifest.GetTotalSize(),
  475. Digest: digest,
  476. ModifiedAt: info.ModTime(),
  477. })
  478. }
  479. return nil
  480. }
  481. if err := filepath.Walk(fp, walkFunc); err != nil {
  482. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  483. return
  484. }
  485. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  486. }
  487. func CopyModelHandler(c *gin.Context) {
  488. var req api.CopyRequest
  489. err := c.ShouldBindJSON(&req)
  490. switch {
  491. case errors.Is(err, io.EOF):
  492. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  493. return
  494. case err != nil:
  495. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  496. return
  497. }
  498. if req.Source == "" || req.Destination == "" {
  499. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
  500. return
  501. }
  502. if err := CopyModel(req.Source, req.Destination); err != nil {
  503. if os.IsNotExist(err) {
  504. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  505. } else {
  506. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  507. }
  508. return
  509. }
  510. }
  511. var defaultAllowOrigins = []string{
  512. "localhost",
  513. "127.0.0.1",
  514. "0.0.0.0",
  515. }
  516. func Serve(ln net.Listener, allowOrigins []string) error {
  517. config := cors.DefaultConfig()
  518. config.AllowWildcard = true
  519. config.AllowOrigins = allowOrigins
  520. for _, allowOrigin := range defaultAllowOrigins {
  521. config.AllowOrigins = append(config.AllowOrigins,
  522. fmt.Sprintf("http://%s", allowOrigin),
  523. fmt.Sprintf("https://%s", allowOrigin),
  524. fmt.Sprintf("http://%s:*", allowOrigin),
  525. fmt.Sprintf("https://%s:*", allowOrigin),
  526. )
  527. }
  528. workDir, err := os.MkdirTemp("", "ollama")
  529. if err != nil {
  530. return err
  531. }
  532. defer os.RemoveAll(workDir)
  533. r := gin.Default()
  534. r.Use(
  535. cors.New(config),
  536. func(c *gin.Context) {
  537. c.Set("workDir", workDir)
  538. c.Next()
  539. },
  540. )
  541. r.POST("/api/pull", PullModelHandler)
  542. r.POST("/api/generate", GenerateHandler)
  543. r.POST("/api/embeddings", EmbeddingHandler)
  544. r.POST("/api/create", CreateModelHandler)
  545. r.POST("/api/push", PushModelHandler)
  546. r.POST("/api/copy", CopyModelHandler)
  547. r.DELETE("/api/delete", DeleteModelHandler)
  548. r.POST("/api/show", ShowModelHandler)
  549. for _, method := range []string{http.MethodGet, http.MethodHead} {
  550. r.Handle(method, "/", func(c *gin.Context) {
  551. c.String(http.StatusOK, "Ollama is running")
  552. })
  553. r.Handle(method, "/api/tags", ListModelsHandler)
  554. }
  555. log.Printf("Listening on %s (version %s)", ln.Addr(), version.Version)
  556. s := &http.Server{
  557. Handler: r,
  558. }
  559. // listen for a ctrl+c and stop any loaded llm
  560. signals := make(chan os.Signal, 1)
  561. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  562. go func() {
  563. <-signals
  564. if loaded.runner != nil {
  565. loaded.runner.Close()
  566. }
  567. os.RemoveAll(workDir)
  568. os.Exit(0)
  569. }()
  570. if runtime.GOOS == "linux" {
  571. // check compatibility to log warnings
  572. if _, err := llm.CheckVRAM(); err != nil {
  573. log.Printf("Warning: GPU support may not enabled, check you have installed install GPU drivers: %v", err)
  574. }
  575. }
  576. return s.Serve(ln)
  577. }
  578. func waitForStream(c *gin.Context, ch chan interface{}) {
  579. c.Header("Content-Type", "application/json")
  580. for resp := range ch {
  581. switch r := resp.(type) {
  582. case api.ProgressResponse:
  583. if r.Status == "success" {
  584. c.JSON(http.StatusOK, r)
  585. return
  586. }
  587. case gin.H:
  588. if errorMsg, ok := r["error"].(string); ok {
  589. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  590. return
  591. } else {
  592. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  593. return
  594. }
  595. default:
  596. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  597. return
  598. }
  599. }
  600. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  601. }
  602. func streamResponse(c *gin.Context, ch chan any) {
  603. c.Header("Content-Type", "application/x-ndjson")
  604. c.Stream(func(w io.Writer) bool {
  605. val, ok := <-ch
  606. if !ok {
  607. return false
  608. }
  609. bts, err := json.Marshal(val)
  610. if err != nil {
  611. log.Printf("streamResponse: json.Marshal failed with %s", err)
  612. return false
  613. }
  614. // Delineate chunks with new-line delimiter
  615. bts = append(bts, '\n')
  616. if _, err := w.Write(bts); err != nil {
  617. log.Printf("streamResponse: w.Write failed with %s", err)
  618. return false
  619. }
  620. return true
  621. })
  622. }