routes.go 11 KB

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