routes.go 13 KB

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