routes.go 16 KB

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