routes.go 16 KB

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