routes.go 19 KB

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